github.com/angenalZZZ/gofunc@v0.0.0-20210507121333-48ff1be3917b/f/goroutines_test.go (about) 1 package f_test 2 3 import ( 4 "github.com/angenalZZZ/gofunc/f" 5 "sync" 6 "sync/atomic" 7 "testing" 8 "time" 9 ) 10 11 func TestGoroutines(t *testing.T) { 12 defer f.GoHandle.Release() 13 14 var sum int32 15 myFunc := func(i interface{}) { 16 n := i.(int32) 17 atomic.AddInt32(&sum, n) 18 } 19 demoFunc := func() { 20 time.Sleep(10 * time.Millisecond) 21 } 22 23 // Use the common pool. 24 runTimes := 1000 25 var wg sync.WaitGroup 26 syncCalculateSum := func() { 27 demoFunc() 28 wg.Done() 29 } 30 for i := 0; i < runTimes; i++ { 31 wg.Add(1) 32 _ = f.GoHandle.Submit(syncCalculateSum) 33 } 34 wg.Wait() 35 goroutines := f.GoHandle.Running() 36 t.Logf("running goroutines: %d\n", goroutines) 37 t.Log("finish all tasks.") 38 39 // Use the pool with a function, 40 // set 10 to the capacity of goroutine pool and 1 second for expired duration. 41 p, _ := f.GoWithFunc(20, func(i interface{}) { 42 myFunc(i) 43 wg.Done() 44 }) 45 defer p.Release() 46 // Submit tasks one by one. 47 for i := 0; i < runTimes; i++ { 48 wg.Add(1) 49 _ = p.Invoke(int32(i)) 50 } 51 wg.Wait() 52 t.Logf("running goroutines: %d\n", p.Running()) 53 t.Logf("finish all tasks, result is %d\n", sum) 54 }