-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathroutine_pool.go
65 lines (58 loc) · 1.02 KB
/
routine_pool.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
63
64
65
package goroutine
import (
"github.com/lvyahui8/ellyn/sdk/common/collections"
)
type Runnable func()
type RoutinePool struct {
buf *collections.LinkedQueue[Runnable]
routineNum int
closed bool
ignorePanic bool
}
func NewRoutinePool(routineNum int, ignorePanic bool) *RoutinePool {
pool := &RoutinePool{
buf: collections.NewLinkedQueue[Runnable](0),
routineNum: routineNum,
ignorePanic: ignorePanic,
}
pool.init()
return pool
}
func (p *RoutinePool) init() {
for i := 0; i < p.routineNum; i++ {
go func() {
for {
if p.closed {
return
}
r, success := p.buf.Dequeue()
if !success {
continue
}
func() {
if p.ignorePanic {
defer func() {
_ = recover()
}()
}
r()
}()
}
}()
}
}
func (p *RoutinePool) Submit(r Runnable) {
if p.closed {
panic("routine pool has closed")
}
_ = p.buf.Enqueue(r)
}
func (p *RoutinePool) Shutdown() {
p.closed = true
go func() {
// 清空队列
for {
_, _ = p.buf.Dequeue()
}
}()
}