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()
}
相关推荐
jerryinwuhan5 小时前
基于各城市站点流量的复合功能比较
开发语言·php
candyTong5 小时前
Claude Code Agent Teams:多 Agent 协作的生命周期与实现机制
后端·架构
迈巴赫车主6 小时前
Java基础:list、set、map一遍过
java·开发语言
南 阳7 小时前
Python从入门到精通day66
开发语言·python
十八旬8 小时前
快速安装ClaudeCode完整指南
开发语言·windows·python·claude
前进的李工8 小时前
EXPLAIN输出格式全解析:JSON、TREE与可视化
开发语言·数据库·mysql·性能优化·explain
Byron Loong9 小时前
【c++】为什么有了dll和.h,还需要包含lib
java·开发语言·c++
独隅9 小时前
CodeX + Visual Studio Code 联动的全面指南
开发语言·php
坚果派·白晓明9 小时前
【鸿蒙PC三方库移植适配框架解读系列】第一篇:Lycium C/C++ 三方库适配 — 概述与环境配置
c语言·开发语言·c++·harmonyos·开源鸿蒙·三方库·c/c++三方库
爱吃小白兔的猫9 小时前
LPA算法详解:一种近线性时间的图社区发现方法
开发语言·php