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

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.xdnf.cn/news/12607.html

相关文章:

  • 今天对C语言中static和extern关键字的作用认识又深刻了
  • Mysql 插入中文乱码
  • 牛客练习赛140
  • 广东餐饮服务中高级证备考指南:高效学习与应试技巧
  • H_Prj06_02 8088单板机串口读取内存块
  • 瀑布流布局
  • Vue2 模板中使用可选链操作符(?.)的坑
  • gRPC 的四种通信模式完整示例
  • 自动驾驶---SD图导航的规划策略
  • 【CSS-5】掌握CSS文本样式:从基础到高级技巧
  • C# 中替换多层级数据的 Id 和 ParentId,保持主从或父子关系不变
  • Python_day47
  • burpsuite安装与入门使用
  • 【C++特殊工具与技术】优化内存分配(二):allocator类
  • excel中数字不满六位在左侧前面补0的方法
  • 数据通信与计算机网络——数字传输
  • Redis:过期删除策略与内存淘汰策略的解析指南
  • 如何处理双面沉金线路板上的定位孔?
  • 如何在Lyra Starter Game中使用EOS(Epic Online Services)
  • python将图片颜色显示在三维坐标系
  • Qt学习及使用_第1部分_认识Qt---学习目的及技术准备
  • 集运维_安装centso7.9和麒麟v10国产系统
  • Redis主从复制原理二 之 主从复制工作流程
  • C++2025.6.7 C++五级考题
  • CADisplayLink、NSTimer、GCD定时器
  • Spring AI与Spring Modulith核心技术解析
  • python打卡第45天
  • LVGL手势识别事件无上报问题处理记录
  • 【补题】Codeforces Round 715 (Div. 2) C. The Sports Festival
  • ubuntu20使用自主探索算法explore_lite实现机器人自主探索导航建图