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()
}
相关推荐
XiaQ0919几秒前
Linux 常用命令学习笔记(用户管理篇):用户、组与权限的钥匙
linux·开发语言·笔记·学习
不可求~5 分钟前
C++ 报错交给 AI 之前,先准备好这 8 类信息
开发语言·c++·人工智能
名字还没想好☜9 分钟前
用 Python struct 解析二进制协议:pack/unpack、字节序与对齐踩坑
开发语言·python·二进制·struct
天涯明月199328 分钟前
SGLang深度研究报告
人工智能·后端·推理·sglang
一知半解仙32 分钟前
当机器人学会泛化,而我在写Java:一名后端开发者的2026年8月21日观察手记
java·开发语言·机器人
程序员爱钓鱼1 小时前
Rust where详解:让泛型与Trait约束更加清晰
前端·后端·rust
青 春 记 忆1 小时前
LeetCode 155. 最小栈|Python 解法详解
开发语言·python·leetcode
程序员爱钓鱼3 小时前
Go 编程实战:函数 Function——参数、返回值与代码复用
后端·面试·go
To_OC8 小时前
跑了3个Docker容器后,我终于搞懂镜像和容器到底啥关系
后端·docker·容器
东风破_9 小时前
Docker 基础:为什么需要容器?
前端·后端·nginx