Golang 批量执行/并发执行

提到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()
}
相关推荐
茉莉玫瑰花茶15 小时前
GO [ 泛型 ]
golang
weixin_4407305016 小时前
函数return、参数、参数组、递归函数、高阶函数等小结
开发语言·python
苏supper16 小时前
Spring Boot多环境配置与打包运行
spring boot·后端·spring
sugarzhangnotes16 小时前
【无标题】
开发语言·人工智能·python
geovindu16 小时前
rust: Composite Pattern
开发语言·后端·设计模式·rust·组合模式
SearchMan17 小时前
还有人不知道&和&&的区别?
后端
想用offer打牌17 小时前
Personal Agent爆火 - 它到底是个什么
人工智能·后端·ai编程
IT_陈寒17 小时前
Vue的v-if和v-for混用居然是个天坑
前端·人工智能·后端
周杰偷奶茶18 小时前
【Java】数组的定义和使用(附管理系统实战案例)
java·开发语言
橙子圆12318 小时前
JUC之集合类不安全
java·开发语言