1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
pool.go 2.58 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2023-05-30 14:27 . job
package scheduler
import (
"gitee.com/h79/goutils/common/system"
"sync/atomic"
)
type IdleHandler interface {
Idle(num int32)
}
// IdleFunc idle working number
type IdleFunc func(num int32)
func (fn IdleFunc) Idle(num int32) {
fn(num)
}
type Pool struct {
jobs chan *Job
workers chan *jobWorker
stop chan bool
numWorkers int32 //总数
runWorkers int32 //正常运行
idleWorking int32 //空闲worker数
idleHandler IdleHandler
running system.RunningCheck
}
func NewPool(numWorkers, jobQueueLen int) *Pool {
if numWorkers <= 0 || jobQueueLen <= 0 {
panic("length is zero")
}
var num = int32(numWorkers)
pool := &Pool{
jobs: make(chan *Job, jobQueueLen),
workers: make(chan *jobWorker, numWorkers),
stop: make(chan bool),
numWorkers: num,
runWorkers: num,
idleWorking: num,
}
pool.createWorkers(numWorkers)
pool.Run()
return pool
}
func (p *Pool) SetIdleHandler(fn IdleHandler) *Pool {
p.idleHandler = fn
return p
}
func (p *Pool) WithIdleFunc(fn func(num int32)) *Pool {
return p.SetIdleHandler(IdleFunc(fn))
}
func (p *Pool) AddJob(job *Job) {
if job == nil {
return
}
ww := atomic.LoadInt32(&p.runWorkers)
if ww <= p.numWorkers/2 {
// 中间有原因,线程池中的线程,由于某些原因,退出了,需要再启动
p.createWorkers(int(p.numWorkers - ww))
}
p.jobs <- job
}
func (p *Pool) Run() {
p.running.TryGoRunning(p.dispatch)
}
func (p *Pool) HasWorking() bool {
return atomic.LoadInt32(&p.idleWorking) != p.numWorkers
}
func (p *Pool) Release() {
p.stop <- true
<-p.stop
p.idleHandle(p.numWorkers)
}
func (p *Pool) createWorkers(num int) {
for i := 0; i < num; i++ {
worker := newWorker(p)
worker.start()
}
}
func (p *Pool) idleHandle(idleWork int32) {
if p.idleHandler != nil {
p.idleHandler.Idle(idleWork)
}
}
func (p *Pool) workerRunning() {
atomic.AddInt32(&p.runWorkers, 1)
}
func (p *Pool) workerQuit() {
atomic.AddInt32(&p.runWorkers, -1)
}
func (p *Pool) workerIdle() {
p.idleHandle(atomic.AddInt32(&p.idleWorking, 1))
}
func (p *Pool) dispatch() {
defer p.idleHandle(p.numWorkers)
var exit = system.Exit()
for {
select {
case <-exit.Done():
p.stop <- true
case job := <-p.jobs:
worker := <-p.workers
p.idleHandle(atomic.AddInt32(&p.idleWorking, -1))
worker.timeout = job.Timeout
worker.job <- job
case <-p.stop:
for i := 0; i < cap(p.workers); i++ {
worker := <-p.workers
worker.stop <- true
<-worker.stop
}
atomic.StoreInt32(&p.idleWorking, p.numWorkers)
p.stop <- true
return
case <-system.Closed():
p.stop <- true
}
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.8.6

搜索帮助

344bd9b3 5694891 D2dac590 5694891