github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/zutil/once_test.go (about)

     1  package zutil_test
     2  
     3  import (
     4  	"sync"
     5  	"testing"
     6  
     7  	"github.com/sohaha/zlsgo"
     8  	"github.com/sohaha/zlsgo/zutil"
     9  )
    10  
    11  func TestOnce(t *testing.T) {
    12  	tt := zlsgo.NewTest(t)
    13  	var v = 1
    14  	var r = zutil.Once(func() interface{} {
    15  		v = v + 1
    16  		return v
    17  	})
    18  	var wg sync.WaitGroup
    19  	for i := 0; i < 100; i++ {
    20  		wg.Add(1)
    21  		go func() {
    22  			defer wg.Done()
    23  			value := (r()).(int)
    24  			tt.Equal(2, value)
    25  		}()
    26  	}
    27  	wg.Wait()
    28  }
    29  
    30  func TestOnceNested(t *testing.T) {
    31  	tt := zlsgo.NewTest(t)
    32  	var v = 1
    33  	var r = zutil.Once(func() interface{} {
    34  		v = v + 1
    35  		return v
    36  	})
    37  
    38  	var v2 = 2
    39  	var r2 = zutil.Once(func() interface{} {
    40  		v2 = r().(int) + 2
    41  		return v2
    42  	})
    43  
    44  	var wg sync.WaitGroup
    45  	for i := 0; i < 100; i++ {
    46  		wg.Add(1)
    47  		go func() {
    48  			defer wg.Done()
    49  			value := (r2()).(int)
    50  			tt.Equal(4, value)
    51  		}()
    52  	}
    53  	wg.Wait()
    54  }