// 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) }
// 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 time.Duration
// WithExpiryDuration sets up the interval time of cleaning up goroutines. funcWithExpiryDuration(expiryDuration time.Duration) Option { returnfunc(opts *Options) { opts.ExpiryDuration = expiryDuration } }
// WithPreAlloc indicates whether it should malloc for workers. funcWithPreAlloc(preAlloc bool) Option { returnfunc(opts *Options) { opts.PreAlloc = preAlloc } }
// WithMaxBlockingTasks sets up the maximum number of goroutines that are blocked when it reaches the capacity of pool. funcWithMaxBlockingTasks(maxBlockingTasks int) Option { returnfunc(opts *Options) { opts.MaxBlockingTasks = maxBlockingTasks } }
// WithNonblocking indicates that pool will return nil when there is no available workers. funcWithNonblocking(nonblocking bool) Option { returnfunc(opts *Options) { opts.Nonblocking = nonblocking } }