-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtaskPool.go
124 lines (102 loc) · 2.12 KB
/
taskPool.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package concurrent
import (
"sync"
"sync/atomic"
)
type Task func()
type TaskPool struct {
queue chan Task
queueSize int32
workersSize int32
accept *AtomicBoolean
done chan struct{}
finishWaiter sync.WaitGroup
errorHandler func()
}
func NewTaskPool(workers int, errorHandlers ...func(interface{})) *TaskPool {
pool := &TaskPool{
queue: make(chan Task, workers),
accept: AtomicBooleanOf(true),
done: make(chan struct{}),
workersSize: int32(workers),
}
if len(errorHandlers) > 0 && errorHandlers[0] != nil {
pool.errorHandler = func() {
if err := recover(); err != nil {
errorHandlers[0](err)
}
}
} else {
pool.errorHandler = func() {}
}
for i := 0; i < workers; i++ {
go pool.doWork()
}
return pool
}
func (pool *TaskPool) queueTask(task Task) {
if pool.accept.Get() {
defer pool.errorHandler()
atomic.AddInt32(&pool.queueSize, 1)
pool.queue <- task
}
}
// submits a task waiting if necessary
func (pool *TaskPool) SubmitSync(task Task) {
if pool.accept.Get() {
pool.registerWork()
pool.queueTask(task)
}
}
// returns true if submit was not waiting
func (pool *TaskPool) Submit(task Task) bool {
immediate := false
if pool.accept.Get() {
pool.registerWork()
immediate = atomic.LoadInt32(&pool.queueSize) < pool.workersSize
if immediate {
pool.queueTask(task)
} else {
go pool.queueTask(task)
}
}
return immediate
}
func (pool *TaskPool) Shutdown() {
pool.accept.Set(false)
pool.done <- struct{}{}
close(pool.queue)
close(pool.done)
atomic.StoreInt32(&pool.queueSize, 0)
}
func (pool *TaskPool) doWork() {
for {
select {
case task := <-pool.queue:
atomic.AddInt32(&pool.queueSize, -1)
if task == nil {
continue
}
pool.doTask(task)
case <-pool.done:
return
}
}
}
func (pool *TaskPool) doTask(task Task) {
defer func() {
pool.errorHandler()
pool.doneWork()
}()
task()
}
func (pool *TaskPool) registerWork() {
pool.finishWaiter.Add(1)
}
func (pool *TaskPool) doneWork() {
pool.finishWaiter.Done()
}
func (pool *TaskPool) WaitForAll() {
defer pool.errorHandler()
pool.finishWaiter.Wait()
}