-
Notifications
You must be signed in to change notification settings - Fork 95
/
Copy pathtask.go
62 lines (54 loc) · 1.08 KB
/
task.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package gws
import (
"sync"
)
type (
workerQueue struct {
mu sync.Mutex // 锁
q []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(delta int32) asyncJob {
c.mu.Lock()
defer c.mu.Unlock()
c.curConcurrency += delta
if c.curConcurrency >= c.maxConcurrency {
return nil
}
if len(c.q) == 0 {
return nil
}
var result = c.q[0]
c.q = c.q[1:]
c.curConcurrency++
return result
}
// 循环执行任务
func (c *workerQueue) do(job asyncJob) {
for job != nil {
job()
job = c.getJob(-1)
}
}
// Push 追加任务, 有资源空闲的话会立即执行
func (c *workerQueue) Push(job asyncJob) {
c.mu.Lock()
c.q = append(c.q, job)
c.mu.Unlock()
if job := c.getJob(0); job != nil {
go c.do(job)
}
}