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()
}
相关推荐
峥嵘life3 分钟前
Android16 开机后立即打开相机闪退问题分析与解决总结
android·开发语言·数码相机·策略模式
niucloud-admin9 分钟前
NIUCLOUD LITE AI开发文档--命名规范
开发语言·php
WL学习笔记10 分钟前
模板初阶(C++)
开发语言·c++·后端·模板初阶
九零HTTP11 分钟前
aiohttp 连接池:那个 limit 参数到底在限什么
后端
SunnyDays101112 分钟前
使用 Java 高效管理 Excel 批注:添加、读取、修改和删除
java·开发语言·excel
花间相见12 分钟前
【计算基础|MySQL06】MySQL 架构与一条 SQL 的旅程
数据库·后端
Thneonl25 分钟前
Spark 比 MR 快在哪?管住最贵的 shuffle
后端·架构
ydjs678899-bot35 分钟前
为什么大型monorepos变慢了Rush.js + Sparo对此做了什么
开发语言·javascript·ecmascript
申君健248641827720240 分钟前
AI SDK 概念全景总结(v7) 二
后端
坊钰42 分钟前
【LangGraph框架入门级】12. 人机交互:interrupt 中断与 Command 恢复
开发语言·数据库·python·人机交互·ai编程·langgraph