提到Golang,都说Golang 天生高并发。所以分享一下我认为的Golang高并发精髓
简单的并发执行util
package util
import ("context""sync"
)type batchRunner struct {BatchSize intctx context.Contextchannel chan func()wg sync.WaitGroup
}func NewBatchRunner(ctx context.Context, batch int) *batchRunner {r := &batchRunner{BatchSize: batch,channel: make(chan func()),ctx: ctx,}for batchIdx := 0; batchIdx < r.BatchSize; batchIdx++ {r.wg.Add(1)go func() {for r.ctx.Err() == nil {f, open := <-r.channelif !open && f == nil {break}f()}r.wg.Done()}()}return r
}func (r *batchRunner) Run(handel func()) {r.channel <- handel
}func (r *batchRunner) Wait() {close(r.channel)r.wg.Wait()
}