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()
}
相关推荐
csdn2015_几秒前
java springboot项目,接收到的参数多个逗号
java·开发语言·spring boot
cui_hao_nan2 分钟前
Spring AOP 自调用、代理与 private 方法引发的诡异 NPE
java·后端·spring·ai开发
可乐鸡翅yeah_11 分钟前
hls.js 多实例并发踩坑,多视频页面播放器内存与冲突问题解决
开发语言·前端·javascript·音视频·hls·m3u8·m3u8在线播放
俊昭喜喜里12 分钟前
c#中的构造函数
开发语言·数据库·c#
gsls20080816 分钟前
告别 Vault 的复杂度:用 Go 标准库给 Windows 凭据管理器装上 MCP
windows·golang·mcp
hahaha601624 分钟前
HLS高层次综合设计--axi之burst纠偏
开发语言·算法·fpga开发·c#
IT_陈寒25 分钟前
JavaScript的隐式转换太坑了,我的==比较怎么就炸了?
前端·人工智能·后端
SunnyDays101131 分钟前
如何使用 Python 给 PDF 添加附件:文档附件与附件注释
开发语言·python·pdf
学逆向的1 小时前
扩展PE头属性说明
开发语言·网络安全·pe
秋名RG1 小时前
Java 基础语法
java·开发语言