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()
}
相关推荐
shykevin26 分钟前
python开发Streamable HTTP MCP应用
开发语言·网络·python·网络协议·http
我不是程序猿儿29 分钟前
【C#】 lock 关键字
java·开发语言·c#
漫路在线1 小时前
JS逆向-某易云音乐下载器
开发语言·javascript·爬虫·python
小辉懂编程1 小时前
C语言:51单片机实现数码管依次循环显示【1~F】课堂练习
c语言·开发语言·51单片机
醍醐三叶2 小时前
C++类与对象--2 对象的初始化和清理
开发语言·c++
Magnum Lehar3 小时前
3d游戏引擎EngineTest的系统实现3
java·开发语言·游戏引擎
就叫飞六吧4 小时前
Spring Security 集成指南:避免 CORS 跨域问题
java·后端·spring
Mcworld8574 小时前
java集合
java·开发语言·windows
成功人chen某4 小时前
配置VScodePython环境Python was not found;
开发语言·python
海绵宝宝贾克斯儿5 小时前
C++中如何实现一个单例模式?
开发语言·c++·单例模式