1 Star 0 Fork 0

websocket2024/gws

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
task.go 1.42 KB
一键复制 编辑 原始数据 按行查看 历史
lxzan 提交于 1年前 . reuse cps/dps slide window
package gws
import (
"sync"
"github.com/lxzan/gws/internal"
)
type (
workerQueue struct {
mu sync.Mutex // 锁
q internal.Deque[asyncJob] // 任务队列
maxConcurrency int32 // 最大并发
curConcurrency int32 // 当前并发
}
asyncJob func()
)
// newWorkerQueue 创建一个任务队列
func newWorkerQueue(maxConcurrency int32) *workerQueue {
c := &workerQueue{
mu: sync.Mutex{},
maxConcurrency: maxConcurrency,
curConcurrency: 0,
}
return c
}
// 获取一个任务
func (c *workerQueue) getJob(newJob asyncJob, delta int32) asyncJob {
c.mu.Lock()
defer c.mu.Unlock()
if newJob != nil {
c.q.PushBack(newJob)
}
c.curConcurrency += delta
if c.curConcurrency >= c.maxConcurrency {
return nil
}
var job = c.q.PopFront()
if job == nil {
return nil
}
c.curConcurrency++
return job
}
// 循环执行任务
func (c *workerQueue) do(job asyncJob) {
for job != nil {
job()
job = c.getJob(nil, -1)
}
}
// Push 追加任务, 有资源空闲的话会立即执行
func (c *workerQueue) Push(job asyncJob) {
if nextJob := c.getJob(job, 0); nextJob != nil {
go c.do(nextJob)
}
}
type channel chan struct{}
func (c channel) add() { c <- struct{}{} }
func (c channel) done() { <-c }
func (c channel) Go(m *Message, f func(*Message) error) error {
c.add()
go func() {
_ = f(m)
c.done()
}()
return nil
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/websocket2024/gws.git
git@gitee.com:websocket2024/gws.git
websocket2024
gws
gws
dev

搜索帮助