Go协程并发复用,降低CPU和内存负载
- 实现简单
- 性能优异
- 采用「生产-消费」模式
- 任务支持context
- 任务队列支持缓冲大小设置
- 非阻塞模式下,任务缓存到全局链表
- 配套设施:errgroup 和 timewheel
go get -u github.com/shenghui0779/nightfall
goos: darwin
goarch: amd64
cpu: Intel(R) Core(TM) i5-1038NG7 CPU @ 2.00GHz
func main() {
ctx := context.Background()
pool := woker.NewPool(5000)
for i := 0; i < 100000000; i++ {
i := i
pool.Go(ctx, func(ctx context.Context) {
time.Sleep(time.Second)
fmt.Println("Index:", i)
})
}
<-ctx.Done()
}
func main() {
ctx := context.Background()
pool, _ := ants.NewPool(5000)
for i := 0; i < 100000000; i++ {
i := i
pool.Submit(func() {
time.Sleep(time.Second)
fmt.Println("Index:", i)
})
}
<-ctx.Done()
}
func main() {
ctx := context.Background()
pool := woker.NewPool(5000)
for i := 0; i < 100; i++ {
i := i
pool.Go(ctx, func(ctx context.Context) {
for j := 0; j < 1000000; j++ {
j := j
pool.Go(ctx, func(ctx context.Context) {
time.Sleep(time.Second)
fmt.Println("Index:", i, "-", j)
})
}
})
}
<-ctx.Done()
}
func main() {
ctx := context.Background()
pool, _ := ants.NewPool(5000)
for i := 0; i < 100; i++ {
i := i
pool.Submit(func() {
for j := 0; j < 1000000; j++ {
j := j
pool.Submit(func() {
time.Sleep(time.Second)
fmt.Println("Index:", i, "-", j)
})
}
})
}
<-ctx.Done()
}