官方示例
package main
import (
"fmt"
"github.com/panjf2000/ants/v2"
"sync"
"sync/atomic"
"time"
)
var sum int32
func myFunc(i interface{}) {
n := i.(int32)
atomic.AddInt32(&sum, n)
fmt.Printf("run with %d\n", n)
}
func demoFunc() {
time.Sleep(10 * time.Second)
fmt.Println("Hello World!")
}
func main() {
defer ants.Release()
runTimes := 10
// 使用公共资源池
var wg sync.WaitGroup
syncCalculateSum := func() {
demoFunc()
wg.Done()
}
for i := 0; i < runTimes; i++ {
wg.Add(1)
_ = ants.Submit(syncCalculateSum)
}
wg.Wait()
fmt.Printf("running goroutines: %d\n", ants.Running())
fmt.Printf("finish all tasks.\n")
// 使用函数池
// 设置10为池的容量
p, _ := ants.NewPoolWithFunc(10, func(i interface{}) {
myFunc(i)
wg.Done()
})
defer p.Release()
// 逐个提交任务
for i := 0; i < runTimes; i++ {
wg.Add(1)
//传参
_ = p.Invoke(int32(i))
}
wg.Wait()
fmt.Printf("running goroutines: %d\n", p.Running())
fmt.Printf("finish all tasks, result is %d\n", sum)
}
普通方式
package main
import (
"fmt"
"sync"
"github.com/panjf2000/ants/v2"
)
func main() {
// 创建一个大小为10的Goroutine池
pool, _ := ants.NewPool(10)
// 等待组,用于等待所有任务完成
var wg sync.WaitGroup
wg.Add(10)
for i := 0; i < 10; i++ {
// 提交任务到池中
pool.Submit(func() {
defer wg.Done()
fmt.Println("Executing task")
})
}
// 等待所有任务完成
wg.Wait()
// 关闭池
pool.Release()
}
标签:wg,10,fmt,ants,Golang,协程池,func,Printf
From: https://www.cnblogs.com/qcy-blog/p/17929878.html