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()
}
相关推荐
时间的情敌13 分钟前
Three.js 射线拾取进阶:hover 高亮、点击弹窗、多物体过滤、穿透拾取
开发语言·javascript·three.js
Amumu1213829 分钟前
TypeScript学习: 基本类型(一)
开发语言·前端·typescript
光影少年1 小时前
ts全栈开发
javascript·后端·typescript·node.js·c5全栈
苍何2 小时前
用 WorkBuddy 自动总结微信群聊消息,夯!
后端
敲上瘾2 小时前
Qt 常用控件:按钮、显示输入、容器与布局等
开发语言·c++·qt·qt6.3
苍何2 小时前
全国产算力模型,近 300B 参数,猛猛干活
后端
bai2732 小时前
主线程里 foo 和 FOO 是同一个变量,Worker 里就成了两个:Windows 上 process.env 的大小写边界
javascript·后端
苍何2 小时前
AI 视频新斩杀线来了,这下给我用爽了(附实测及提示词)
后端
泡海椒2 小时前
Java 生成人事在岗率对比 PDF:应到/实到双系列条形的参数清单
后端
船神丿男人2 小时前
C++ STL 入门:用 std::string 读配置,四个容易漏掉的边界
开发语言·c++