提到Golang,都说Golang 天生高并发。所以分享一下我认为的Golang高并发精髓
简单的并发执行util
go
package util
import (
"context"
"sync"
)
type batchRunner struct {
BatchSize int
ctx context.Context
channel 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.channel
if !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()
}