-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfactotum.go
117 lines (103 loc) · 1.85 KB
/
factotum.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
package factotum
import (
"sync"
)
type WorkRequest interface {
Work() bool
}
type worker struct {
ID int
work chan WorkRequest
workerQueue chan chan WorkRequest
quit chan bool
wait *sync.WaitGroup
}
type WorkerGroup struct {
workerQueue chan chan WorkRequest
WorkQueue chan WorkRequest
workers []*worker
wait *sync.WaitGroup
closed bool
quit chan bool
}
func NewWorker(id int, wq chan chan WorkRequest, wait *sync.WaitGroup) *worker {
worker := &worker{
ID: id,
work: make(chan WorkRequest),
workerQueue: wq,
quit: make(chan bool),
wait: wait,
}
return worker
}
func (w *worker) Start() {
go func() {
defer w.wait.Done()
for {
w.workerQueue <- w.work
select {
case work := <-w.work:
work.Work()
case <-w.quit:
return
}
}
}()
}
func (w *worker) Stop() {
go func() {
close(w.quit)
}()
}
func NewWorkerGroup(n int) (wg *WorkerGroup) {
wg = &WorkerGroup{}
wg.workerQueue = make(chan chan WorkRequest, n)
wg.WorkQueue = make(chan WorkRequest, n*2)
wg.workers = make([]*worker, n)
wg.quit = make(chan bool)
wg.wait = &sync.WaitGroup{}
wg.wait.Add(n)
for i := 0; i < n; i++ {
w := NewWorker(i+1, wg.workerQueue, wg.wait)
wg.workers[i] = w
w.Start()
}
return wg
}
func (wg *WorkerGroup) Start() {
go func() {
for {
select {
case work := <-wg.WorkQueue:
go func() {
worker := <-wg.workerQueue
worker <- work
}()
case <-wg.quit:
return
}
}
}()
}
func (wg *WorkerGroup) Enqueue(w WorkRequest) bool {
if wg.closed {
return false
}
go func() {
wg.WorkQueue <- w
}()
return true
}
func (wg *WorkerGroup) Stop() {
if wg.closed {
return
}
close(wg.quit)
wg.closed = true
for _, w := range wg.workers {
w.Stop()
}
wg.wait.Wait()
close(wg.WorkQueue)
close(wg.workerQueue)
}