package main
import (
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/panjf2000/ants/v2"
)
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.Millisecond)
fmt.Println("Hello World!")
}
func main() {
defer ants.Release() // 预关闭
runTimes := 1000
// 使用池
var wg sync.WaitGroup
syncCalculateSum := func() {
// 打印"Hello World!"
demoFunc()
wg.Done()
}
// 循环1000
for i := 0; i < runTimes; i++ {
wg.Add(1)
// 提交会话到 pool
_ = ants.Submit(syncCalculateSum)
}
wg.Wait()
// ants.Running() 返回当前正在运行的goroutine数。
fmt.Printf("running goroutines: %d\n", ants.Running())
fmt.Printf("finish all tasks.\n")
// Use the pool with a method,
// 将goroutine池的容量设置为10,过期时间设置为1秒。
p, _ := ants.NewPoolWithFunc(10, func(i interface{}) {
myFunc(i)
wg.Done()
})
defer p.Release()
// Submit tasks one by one.
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)
if sum != 499500 {
panic("the final result is wrong!!!")
}
nothing := `
自定义池
ants支持实例化使用者自己的一个
Pool ,指定具体的池容量;通过调用
NewPool
方法可以实例化一个新的带有指定容量的
Pool ,如下:
// Set 10000 the size of goroutine pool
p, _ := ants.NewPool(10000)
任务提交
提交任务通过调用
ants.Submit(func())
方法:
ants.Submit(func() {})
动态调整
goroutine
池容量
需要动态调整
goroutine
池容量可以通过调用Tune(int):
pool.Tune(1000) // Tune its capacity to 1000
pool.Tune(100000) // Tune its capacity to 100000
预先分配
goroutine
队列内存
ants允许你预先把整个池的容量分配内存, 这个功能可以在某些特定的场景下提高
goroutine
池的性能。比如, 有一个场景需要一个超大容量的池,而且每个
goroutine
里面的任务都是耗时任务,这种情况下,预先分配
goroutine
队列内存将会减少不必要的内存重新分配。
// ants will pre-malloc the whole capacity of pool when you invoke this function
p, _ := ants.NewPool(100000, ants.WithPreAlloc(true))
释放
Pool
pool.Release()
重启
Pool
// 只要调用 Reboot() 方法,就可以重新激活一个之前已经被销毁掉的池,并且投入使用。
pool.Reboot()
`
fmt.Println(nothing)
}
go第三方 goroutine 池 库 ants
最新推荐文章于 2024-04-10 22:32:55 发布