### 动态图 ![](https://raw.githubusercontent.com/panjf2000/illustrations/master/go/ants-pool-1.png) ![](https://raw.githubusercontent.com/panjf2000/illustrations/master/go/ants-pool-2.png) ![](https://raw.githubusercontent.com/panjf2000/illustrations/master/go/ants-pool-3.png) ![](https://raw.githubusercontent.com/panjf2000/illustrations/master/go/ants-pool-4.png) ## 🧰 安装 ### 使用 `ants` v1 版本: ``` powershell go get -u github.com/panjf2000/ants ``` ### 使用 `ants` v2 版本 (开启 GO111MODULE=on): ```powershell go get -u github.com/panjf2000/ants/v2 ``` ## 🛠 使用 写 go 并发程序的时候如果程序会启动大量的 goroutine ,势必会消耗大量的系统资源(内存,CPU),通过使用 `ants`,可以实例化一个 goroutine 池,复用 goroutine ,节省资源,提升性能: ``` go 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 // Use the common pool. 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") // Use the pool with a function, // set 10 to the capacity of goroutine pool and 1 second for expired duration. 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!!!") } // Use the MultiPool and set the capacity of the 10 goroutine pools to unlimited. // If you use -1 as the pool size parameter, the size will be unlimited. // There are two load-balancing algorithms for pools: ants.RoundRobin and ants.LeastTasks. mp, _ := ants.NewMultiPool(10, -1, ants.RoundRobin) defer mp.ReleaseTimeout(5 * time.Second) for i := 0; i < runTimes; i++ { wg.Add(1) _ = mp.Submit(syncCalculateSum) } wg.Wait() fmt.Printf("running goroutines: %d\n", mp.Running()) fmt.Printf("finish all tasks.\n") // Use the MultiPoolFunc and set the capacity of 10 goroutine pools to (runTimes/10). mpf, _ := ants.NewMultiPoolWithFunc(10, runTimes/10, func(i interface{}) { myFunc(i) wg.Done() }, ants.LeastTasks) defer mpf.ReleaseTimeout(5 * time.Second) for i := 0; i < runTimes; i++ { wg.Add(1) _ = mpf.Invoke(int32(i)) } wg.Wait() fmt.Printf("running goroutines: %d\n", mpf.Running()) fmt.Printf("finish all tasks, result is %d\n", sum) if sum != 499500*2 { panic("the final result is wrong!!!") } } ``` ### Pool 配置 ```go // Option represents the optional function. type Option func(opts *Options) // Options contains all options which will be applied when instantiating a ants pool. type Options struct { // ExpiryDuration is a period for the scavenger goroutine to clean up those expired workers, // the scavenger scans all workers every `ExpiryDuration` and clean up those workers that haven't been // used for more than `ExpiryDuration`. ExpiryDuration time.Duration // PreAlloc indicates whether to make memory pre-allocation when initializing Pool. PreAlloc bool // Max number of goroutine blocking on pool.Submit. // 0 (default value) means no such limit. MaxBlockingTasks int // When Nonblocking is true, Pool.Submit will never be blocked. // ErrPoolOverload will be returned when Pool.Submit cannot be done at once. // When Nonblocking is true, MaxBlockingTasks is inoperative. Nonblocking bool // PanicHandler is used to handle panics from each worker goroutine. // if nil, panics will be thrown out again from worker goroutines. PanicHandler func(interface{}) // Logger is the customized logger for logging info, if it is not set, // default standard logger from log package is used. Logger Logger } // WithOptions accepts the whole options config. func WithOptions(options Options) Option { return func(opts *Options) { *opts = options } } // WithExpiryDuration sets up the interval time of cleaning up goroutines. func WithExpiryDuration(expiryDuration time.Duration) Option { return func(opts *Options) { opts.ExpiryDuration = expiryDuration } } // WithPreAlloc indicates whether it should malloc for workers. func WithPreAlloc(preAlloc bool) Option { return func(opts *Options) { opts.PreAlloc = preAlloc } } // WithMaxBlockingTasks sets up the maximum number of goroutines that are blocked when it reaches the capacity of pool. func WithMaxBlockingTasks(maxBlockingTasks int) Option { return func(opts *Options) { opts.MaxBlockingTasks = maxBlockingTasks } } // WithNonblocking indicates that pool will return nil when there is no available workers. func WithNonblocking(nonblocking bool) Option { return func(opts *Options) { opts.Nonblocking = nonblocking } } // WithPanicHandler sets up panic handler. func WithPanicHandler(panicHandler func(interface{})) Option { return func(opts *Options) { opts.PanicHandler = panicHandler } } // WithLogger sets up a customized logger. func WithLogger(logger Logger) Option { return func(opts *Options) { opts.Logger = logger } } ``` 通过在调用`NewPool`/`NewPoolWithFunc`之时使用各种 optional function,可以设置`ants.Options`中各个配置项的值,然后用它来定制化 goroutine pool. ### 自定义池 `ants`支持实例化使用者自己的一个 Pool ,指定具体的池容量;通过调用 `NewPool` 方法可以实例化一个新的带有指定容量的 Pool ,如下: ``` go p, _ := ants.NewPool(10000) ``` ### 任务提交 提交任务通过调用 `ants.Submit(func())`方法: ```go ants.Submit(func(){}) ``` ### 动态调整 goroutine 池容量 需要动态调整 goroutine 池容量可以通过调用`Tune(int)`: ``` go pool.Tune(1000) // Tune its capacity to 1000 pool.Tune(100000) // Tune its capacity to 100000 ``` 该方法是线程安全的。 ### 预先分配 goroutine 队列内存 `ants`允许你预先把整个池的容量分配内存, 这个功能可以在某些特定的场景下提高 goroutine 池的性能。比如, 有一个场景需要一个超大容量的池,而且每个 goroutine 里面的任务都是耗时任务,这种情况下,预先分配 goroutine 队列内存将会减少不必要的内存重新分配。 ```go // ants will pre-malloc the whole capacity of pool when you invoke this function p, _ := ants.NewPool(100000, ants.WithPreAlloc(true)) ``` ### 释放 Pool ```go pool.Release() ``` ### 重启 Pool ```go // 只要调用 Reboot() 方法,就可以重新激活一个之前已经被销毁掉的池,并且投入使用。 pool.Reboot() ``` ## ⚙️ 关于任务执行顺序 `ants` 并不保证提交的任务被执行的顺序,执行的顺序也不是和提交的顺序保持一致,因为在 `ants` 是并发地处理所有提交的任务,提交的任务会被分派到正在并发运行的 workers 上去,因此那些任务将会被并发且无序地被执行。 ## 👏 贡献者 请在提 PR 之前仔细阅读 [Contributing Guidelines](CONTRIBUTING.md),感谢那些为 `ants` 贡献过代码的开发者! ## 📄 证书 `ants` 的源码允许用户在遵循 [MIT 开源证书](/LICENSE) 规则的前提下使用。 ## 📚 相关文章 - [Goroutine 并发调度模型深度解析之手撸一个高性能 goroutine 池](https://taohuawu.club/high-performance-implementation-of-goroutine-pool) - [Visually Understanding Worker Pool](https://medium.com/coinmonks/visually-understanding-worker-pool-48a83b7fc1f5) - [The Case For A Go Worker Pool](https://brandur.org/go-worker-pool) - [Go Concurrency - GoRoutines, Worker Pools and Throttling Made Simple](https://twin.sh/articles/39/go-concurrency-goroutines-worker-pools-and-throttling-made-simple) ## 🖥 用户案例 ### 商业公司 以下公司/组织在生产环境上使用了 `ants`。