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()
}
相关推荐
北城以北888822 分钟前
RocketMQ简介
java·spring boot·后端·rocketmq
天天进步201527 分钟前
Python全栈项目--基于机器学习的异常检测系统
开发语言·python·机器学习
GoGeekBaird8 小时前
从 Prompt Engineering 到 Loop Engineering,我觉得 AI 开发这事儿终于开始变味了
后端·github
xxie1237948 小时前
return与print
开发语言·python
秋98 小时前
从 Python 后端工程师转型 AI Engineer(AI 工程化)的完整补课清单(2026实战版)
开发语言·人工智能·python
一条泥憨鱼8 小时前
【Redis】数据类型和常用命令
java·数据库·redis·后端·缓存
程序员二叉8 小时前
【Java】 异常高频面试题精讲 | 易错点+对比总结
java·开发语言·面试
慕木沐9 小时前
Google ADK Java 1.0版本 核心机制与实战 Demo
java·开发语言·python
Oneslide9 小时前
初始化微信小程序
后端
Roann_seo%9 小时前
C++文件操作完全指南:从文本读写到二进制文件处理
开发语言·c++