当前位置: 首页 > article >正文

gopool 源码分析

gopool

gopool是字节跳动开源节流的gopkg包中协程池的一个实现。

关键结构

协程池:

type pool struct {// The name of the poolname string// capacity of the pool, the maximum number of goroutines that are actually working// 协程池的最大容量cap int32// Configuration informationconfig *Config// linked list of tasks// 任务链表taskHead  *tasktaskTail  *tasktaskLock  sync.MutextaskCount int32// Record the number of running workers// 运行中的协程数workerCount int32// This method will be called when the worker panic// 出现 panic 时调用、 panicHandler func(context.Context, interface{})
}

任务:

type task struct {ctx context.Contextf   func()next *task
}

worker:

type worker struct {pool *pool
}

源码分析

先说一下 gopool 的工作流程:

  1. 通过 Go 或者 CtxGo 方法调用
  2. 从 taskPool 中取出一个 t
  3. 如果当前的积压task达到阈值且worker(工作协程)的数量未达到上限,则新建一个worker。

pool.cap 最大工作协程与实际运行的最大协程可能会存在误差。因为新建worker这块不是原子操作:

if (atomic.LoadInt32(&p.taskCount) >= p.config.ScaleThreshold && p.WorkerCount() < atomic.LoadInt32(&p.cap)) || p.WorkerCount() == 0 {// 工作协程加1p.incWorkerCount()w := workerPool.Get().(*worker)w.pool = pw.run()}

worker 的最大数量不会超过pool.cap 。worker run 流程比较简单:

  1. 循环的从 pool 中取出 task 执行

为了方便查看源码,我把相关代码都粘到了下面的,详细流程如下:

var workerPool sync.Poolvar taskPool sync.Pool// 初始化 taskPool
func init() {taskPool.New = newTask
}func (p *pool) Go(f func()) {p.CtxGo(context.Background(), f)
}func (p *pool) CtxGo(ctx context.Context, f func()) {// 从 taskPool 中取 task,避免频繁创建销毁t := taskPool.Get().(*task)t.ctx = ctx// 赋值执行函数t.f = f// 将 t 添加到任务链表里,加锁保证并发安全p.taskLock.Lock()if p.taskHead == nil {p.taskHead = tp.taskTail = t} else {p.taskTail.next = tp.taskTail = t}p.taskLock.Unlock()// 任务链表数量原子加 1atomic.AddInt32(&p.taskCount, 1)// The following two conditions are met:// 1. the number of tasks is greater than the threshold.// 2. The current number of workers is less than the upper limit p.cap.// or there are currently no workers.// 满足以下两个条件:// 1.任务数大于等于设置的阈值(默认为1)// 2.当前的协程数低于上限,或者目前没有工人if (atomic.LoadInt32(&p.taskCount) >= p.config.ScaleThreshold && p.WorkerCount() < atomic.LoadInt32(&p.cap)) || p.WorkerCount() == 0 {// 工作协程加1p.incWorkerCount()w := workerPool.Get().(*worker)w.pool = pw.run()}
}func (w *worker) run() {go func() {for {var t *taskw.pool.taskLock.Lock()if w.pool.taskHead != nil {// 取出任务t = w.pool.taskHeadw.pool.taskHead = w.pool.taskHead.nextatomic.AddInt32(&w.pool.taskCount, -1)}// 没有任务则结束if t == nil {// if there's no task to do, exitw.close()w.pool.taskLock.Unlock()w.Recycle()return}w.pool.taskLock.Unlock()func() {defer func() {if r := recover(); r != nil {if w.pool.panicHandler != nil {w.pool.panicHandler(t.ctx, r)} else {msg := fmt.Sprintf("GOPOOL: panic in pool: %s: %v: %s", w.pool.name, r, debug.Stack())logger.CtxErrorf(t.ctx, msg)}}}()// 执行t.f()}()t.Recycle()}}()
}func (t *task) Recycle() {t.zero()taskPool.Put(t)
}
http://www.lryc.cn/news/2404716.html

相关文章:

  • 【Survival Analysis】【机器学习】【3】 SHAP可解釋 AI
  • ModuleNotFoundError No module named ‘torch_geometric‘未找到
  • iOS 门店营收表格功能的实现
  • 链表题解——环形链表【LeetCode】
  • Cell-o1:强化学习训练LLM解决单细胞推理问题
  • 求解插值多项式及其余项表达式
  • vue3: bingmap using typescript
  • vue3前端实现导出Excel功能
  • 超大规模芯片验证:基于AMD VP1902的S8-100原型验证系统实测性能翻倍
  • 【工作记录】接口功能测试总结
  • Dubbo Logback 远程调用携带traceid
  • 【element-ui】el-autocomplete实现 无数据匹配
  • NLP学习路线图(二十):FastText
  • 力扣面试150题--除法求值
  • SQL进阶之旅 Day 20:锁与并发控制技巧
  • 美业破局:AI智能体如何用数据重塑战略决策(5/6)
  • 生成模型+两种机器学习范式
  • 【学习笔记】Python金融基础
  • 在Linux查看电脑的GPU型号
  • A Execllent Software Project Review and Solutions
  • windows命令行面板升级Git版本
  • Langgraph实战--自定义embeding
  • 大故障,阿里云核心域名疑似被劫持
  • 什么是「镜像」?(Docker Image)
  • SQLMesh实战:用虚拟数据环境和自动化测试重新定义数据工程
  • 服务器健康摩尔斯电码:深度解读S0-S5状态指示灯
  • 设计模式基础概念(行为模式):模板方法模式 (Template Method)
  • 传统业务对接AI-AI编程框架-Rasa的业务应用实战(番外篇2)-- Rasa 训练数据文件的清理
  • LVDS的几个关键电压概念
  • 2023年ASOC SCI2区TOP,随机跟随蚁群优化算法RFACO,深度解析+性能实测