forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
workqueue.go
138 lines (121 loc) · 1.98 KB
/
workqueue.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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
package workqueue
import (
"sync"
"github.com/golang/glog"
)
type Work interface {
Parallel(fn func())
}
type Try interface {
Try(fn func() error)
}
type Interface interface {
Batch(func(Work))
Try(func(Try)) error
Queue(func(Work))
Done()
}
type workQueue struct {
ch chan workUnit
wg *sync.WaitGroup
}
func New(workers int, stopCh <-chan struct{}) Interface {
q := &workQueue{
ch: make(chan workUnit, 100),
wg: &sync.WaitGroup{},
}
go q.run(workers, stopCh)
return q
}
func (q *workQueue) run(workers int, stopCh <-chan struct{}) {
for i := 0; i < workers; i++ {
go func(i int) {
defer glog.V(4).Infof("worker %d stopping", i)
for {
select {
case work, ok := <-q.ch:
if !ok {
return
}
work.fn()
work.wg.Done()
case <-stopCh:
return
}
}
}(i)
}
<-stopCh
}
func (q *workQueue) Batch(fn func(Work)) {
w := &worker{
wg: &sync.WaitGroup{},
ch: q.ch,
}
fn(w)
w.wg.Wait()
}
func (q *workQueue) Try(fn func(Try)) error {
w := &worker{
wg: &sync.WaitGroup{},
ch: q.ch,
err: make(chan error),
}
fn(w)
return w.FirstError()
}
func (q *workQueue) Queue(fn func(Work)) {
w := &worker{
wg: q.wg,
ch: q.ch,
}
fn(w)
}
func (q *workQueue) Done() {
q.wg.Wait()
}
type workUnit struct {
fn func()
wg *sync.WaitGroup
}
type worker struct {
wg *sync.WaitGroup
ch chan workUnit
err chan error
}
func (w *worker) FirstError() error {
done := make(chan struct{})
go func() {
w.wg.Wait()
close(done)
}()
for {
select {
case err := <-w.err:
if err != nil {
return err
}
case <-done:
return nil
}
}
}
func (w *worker) Parallel(fn func()) {
w.wg.Add(1)
w.ch <- workUnit{wg: w.wg, fn: fn}
}
func (w *worker) Try(fn func() error) {
w.wg.Add(1)
w.ch <- workUnit{
wg: w.wg,
fn: func() {
err := fn()
if w.err == nil {
// TODO: have the work queue accumulate errors and release them with Done()
glog.Errorf("Worker error: %v", err)
return
}
w.err <- err
},
}
}