Files
2026-08-17 13:19:15 +08:00

35 lines
1.0 KiB
Go

package common
import (
"context"
"sync"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/grpool"
)
// 协程池封装(grpool):异步任务一律经 Submit 提交,禁止裸 go 启动并行工作负载。
// 并发度来源:config.yml pool.<name>(缺失或非法回退调用方传入的业务默认值,定义在 styleagent/consts)。
// 防死锁:等待链单向(主 → 池),池内任务不得再等待其他池。
type taskPool struct {
size int
once sync.Once
pool *grpool.Pool
}
var pools sync.Map // name → *taskPool
// Submit 提交任务到命名池。ctx 建议传 gctx.New()(请求结束后任务不中断)。
func Submit(ctx context.Context, name string, defaultSize int, fn func(ctx context.Context)) error {
v, _ := pools.LoadOrStore(name, &taskPool{size: defaultSize})
tp := v.(*taskPool)
tp.once.Do(func() {
if n := g.Cfg().MustGet(ctx, "pool."+name, defaultSize).Int(); n > 0 {
tp.size = n
}
tp.pool = grpool.New(tp.size)
})
return tp.pool.Add(ctx, fn)
}