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()
}
相关推荐
巴塞罗那的风7 分钟前
Eino框架快速搭建出行agent(二)引入12306 mcp
人工智能·golang·mcp
刘一说8 分钟前
深入理解 Spring Boot Actuator:构建可观测性与运维友好的应用
运维·spring boot·后端
oak隔壁找我13 分钟前
Spring AI 入门教程,使用Ollama本地模型集成,实现对话记忆功能。
java·人工智能·后端
懒羊羊不懒@14 分钟前
JavaSe—Stream流☆
java·开发语言·数据结构
郝开15 分钟前
最终 2.x 系列版本)2 - 框架搭建:pom配置;多环境配置文件配置;多环境数据源配置;测试 / 生产多环境数据源配置
java·spring boot·后端
Js_cold28 分钟前
(* clock_buffer_type=“NONE“ *)
开发语言·fpga开发·verilog·vivado·buffer·clock
南囝coding34 分钟前
100% 用 AI 做完一个新项目,从 Plan 到 Finished 我学到了这些
前端·后端
Homeey36 分钟前
深入理解ThreadLocal:从原理到架构实践的全面解析
java·后端
周杰伦_Jay41 分钟前
【Go微服务框架深度对比】Kratos、Go-Zero、Go-Micro、GoFrame、Sponge五大框架
开发语言·微服务·golang
杰瑞哥哥1 小时前
标准 Python 项目结构
开发语言·python