Contents

go第三方库-github.com.panjf2000.ants

godoc

github官网

github中文文档

ants是一个开源的go协程池(goruntine池)。使用很方便。

简单使用

使用ants默认的协程池

1
2
//提交需要执行的函数
ants.Submit(syncCalculateSum)

通常和sync.waitgroup一起使用。在main里面使用wg.Add()和wg.Wait,然后在函数中使用wg.Done()。

自定义池

自定义一个协程池,支持选项模式配置,具体看官网

1
2
3
4
5
6
// Set 10000 the size of goroutine pool
p, _ := ants.NewPool(10000)
//提交任务
p.Submit(func(){})
//动态调整 goroutine 池容量
pool.Tune(1000) // Tune its capacity to 1000

释放和重启pool

协程池需要被释放,通常和defer配合使用

1
2
//释放 Pool
pool.Release()

之前销毁的池可以通过重启来重新激活

1
2
//重启 Pool
pool.Reboot()

通过函数构造池

直接生成专门调用某个函数的协程池

1
2
3
4
p, _ := ants.NewPoolWithFunc(10, func(i interface{}) {
  myFunc(i)
  wg.Done()
})

调用协程

1
p.Invoke(int32(i))
 |