-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpool.go
88 lines (78 loc) · 1.38 KB
/
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package waitpool
import (
"context"
"sync"
)
type WaitWorkerPool struct {
wg *sync.WaitGroup
queue chan func()
discardTasks bool
mutex sync.RWMutex
}
func (w *WaitWorkerPool) close() {
w.mutex.Lock()
w.discardTasks = true
close(w.queue)
w.mutex.Unlock()
// drain the remaining tasks in the queue and end them
for {
select {
case _, ok := <-w.queue:
if !ok {
return
}
w.wg.Done()
}
}
}
func (w *WaitWorkerPool) AddTask(fn func()) {
w.mutex.RLock()
defer w.mutex.RUnlock()
if w.discardTasks {
return
}
w.wg.Add(1)
w.queue <- fn
}
func Do(workers int, fn func(pool *WaitWorkerPool)) {
ctx, cancel := context.WithCancel(context.Background())
DoWithContext(ctx, workers, fn)
cancel()
}
func DoWithContext(ctx context.Context, workers int, fn func(pool *WaitWorkerPool)) {
pool := &WaitWorkerPool{wg:&sync.WaitGroup{}, queue: make(chan func(), workers)}
for w := 0; w < workers; w++ {
go func() {
for {
select {
case task, ok := <-pool.queue:
if !ok {
continue
}
task()
pool.wg.Done()
case <-ctx.Done():
return
}
}
} ()
}
done := make(chan struct{}, 1)
go func() {
fn(pool)
pool.wg.Wait()
done <- struct{}{}
} ()
// wait for the tasks to finish or the cancel
drained := false
select {
case <-done:
drained = true
case <-ctx.Done():
}
pool.close()
if !drained {
<- done
}
close(done)
}