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()
}
相关推荐
咖啡の猫2 小时前
Python字典推导式
开发语言·python
leiming62 小时前
C++ vector容器
开发语言·c++·算法
掘金码甲哥2 小时前
🚀糟糕,我实现的k8s informer好像是依托答辩
后端
SystickInt2 小时前
C语言 strcpy和memcpy 异同/区别
c语言·开发语言
GoGeekBaird2 小时前
Andrej Karpathy:2025年大模型发展总结
后端·github
CS Beginner3 小时前
【C语言】windows下编译mingw版本的glew库
c语言·开发语言·windows
uzong3 小时前
听一听技术面试官的心路历程:他们也会有瓶颈,也会表现不如人意
后端
Jimmy3 小时前
年终总结 - 2025 故事集
前端·后端·程序员
FJW0208143 小时前
Python_work4
开发语言·python
大学生资源网3 小时前
java毕业设计之儿童福利院管理系统的设计与实现(源码+)
java·开发语言·spring boot·mysql·毕业设计·源码·课程设计