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()
}
相关推荐
世界哪有真情4 分钟前
用虚拟IP扩容端口池:解决高并发WebSocket端口耗尽问题
前端·后端·websocket
0wioiw07 分钟前
Python基础(吃洋葱小游戏)
开发语言·python·pygame
知其然亦知其所以然12 分钟前
JVM社招面试题:队列和栈是什么?有什么区别?我在面试现场讲了个故事…
java·后端·面试
栗子~~15 分钟前
Python实战- Milvus 向量库 使用相关方法demo
开发语言·python·milvus
武子康16 分钟前
大数据-30 ZooKeeper Java-API 监听节点 创建、删除节点
大数据·后端·zookeeper
知了一笑16 分钟前
SpringBoot3集成多款主流大模型
spring boot·后端·openai
狐凄17 分钟前
Python实例题:基于 Flask 的在线聊天系统
开发语言·python
狐凄17 分钟前
Python实例题:基于 Flask 的任务管理系统
开发语言·python
wmze18 分钟前
InnoDB存储引擎--索引与锁
后端
星辰大海的精灵21 分钟前
如何确保全球数据管道中的跨时区数据完整性和一致性
java·后端·架构