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

     1  package zsync
     2  
     3  import (
     4  	"sync"
     5  	"testing"
     6  
     7  	"github.com/sohaha/zlsgo"
     8  	"github.com/sohaha/zlsgo/zlog"
     9  	"github.com/sohaha/zlsgo/zutil"
    10  )
    11  
    12  func TestWaitGroup(t *testing.T) {
    13  	t.Run("base", func(t *testing.T) {
    14  		tt := zlsgo.NewTest(t)
    15  		t.Parallel()
    16  		count := zutil.NewInt64(0)
    17  		var wg WaitGroup
    18  		for i := 0; i < 100; i++ {
    19  			wg.Go(func() {
    20  				count.Add(1)
    21  			})
    22  		}
    23  		err := wg.Wait()
    24  		tt.NoError(err)
    25  		tt.Equal(int64(100), count.Load())
    26  	})
    27  
    28  	t.Run("err", func(t *testing.T) {
    29  		tt := zlsgo.NewTest(t)
    30  		t.Parallel()
    31  		count := zutil.NewInt64(0)
    32  		var wg WaitGroup
    33  		for i := 0; i < 100; i++ {
    34  			var ii = i
    35  			wg.GoTry(func() {
    36  				count.Add(1)
    37  				if ii > 0 && ii%5 == 0 {
    38  					panic("manual panic")
    39  				}
    40  			})
    41  		}
    42  		err := wg.Wait()
    43  		tt.EqualTrue(err != nil)
    44  		t.Logf("%+v", err)
    45  		zlog.Error(err)
    46  		tt.Equal(int64(100), count.Load())
    47  	})
    48  }
    49  
    50  func BenchmarkWaitGroup_Go(b *testing.B) {
    51  	var wg sync.WaitGroup
    52  	var count int64
    53  	b.ResetTimer()
    54  	for i := 0; i < b.N; i++ {
    55  		wg.Add(1)
    56  		go func() {
    57  			count++
    58  			wg.Done()
    59  		}()
    60  	}
    61  	wg.Wait()
    62  }