github.com/qiuhoude/go-web@v0.0.0-20220223060959-ab545e78f20d/prepare/25_ants/base_use/main.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "github.com/panjf2000/ants/v2" 6 "sync" 7 "sync/atomic" 8 "time" 9 ) 10 11 var sum int32 12 13 func myFunc(i interface{}) { 14 n := i.(int32) 15 atomic.AddInt32(&sum, n) 16 fmt.Printf("run with %d\n", n) 17 } 18 19 func demoFunc() { 20 time.Sleep(10 * time.Millisecond) 21 fmt.Println("Hello World!") 22 } 23 24 func commonPoolDemo(runTimes int) { 25 defer ants.Release() 26 27 var wg sync.WaitGroup 28 29 // Use the common pool. 30 syncCalculateSum := func() { 31 demoFunc() 32 wg.Done() 33 } 34 35 for i := 0; i < runTimes; i++ { 36 wg.Add(1) 37 _ = ants.Submit(syncCalculateSum) // 提交任务 38 } 39 40 wg.Wait() 41 fmt.Printf("running goroutines: %d\n", ants.Running()) 42 fmt.Printf("finish all tasks.\n") 43 } 44 45 func funcPoolDemo(runTimes int) { 46 var wg sync.WaitGroup 47 // Use the pool with a function, 48 // set 10 to the capacity of goroutine pool and 1 second for expired duration. 49 p, _ := ants.NewPoolWithFunc(10, func(i interface{}) { 50 myFunc(i) 51 wg.Done() 52 }, ants.WithPreAlloc(true)) 53 defer p.Release() 54 // Submit tasks one by one. 55 for i := 0; i < runTimes; i++ { 56 wg.Add(1) 57 _ = p.Invoke(int32(i)) 58 } 59 wg.Wait() 60 fmt.Printf("running goroutines: %d\n", p.Running()) 61 fmt.Printf("finish all tasks, result is %d\n", sum) 62 } 63 64 func customPoolDemo(runTimes int) { 65 var wg sync.WaitGroup 66 p, _ := ants.NewPool(1, ants.WithPreAlloc(true)) 67 defer p.Release() 68 69 for i := 0; i < runTimes; i++ { 70 wg.Add(1) 71 param := int32(i) 72 _ = p.Submit(func() { 73 myFunc(param) 74 //demoFunc() 75 wg.Done() 76 }) // 提交任务 77 } 78 79 wg.Wait() 80 fmt.Printf("running goroutines: %d\n", p.Running()) 81 fmt.Printf("finish all tasks, result is %d\n", sum) 82 } 83 84 func main() { 85 commonPoolDemo(100) 86 //funcPoolDemo(100) 87 //customPoolDemo(100) 88 }