-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathworker.go
More file actions
49 lines (43 loc) · 723 Bytes
/
worker.go
File metadata and controls
49 lines (43 loc) · 723 Bytes
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
package queue
import (
"sync"
)
// create a worker thread
func newWorker(pool chan chan Jober, wg *sync.WaitGroup) *worker {
return &worker{
pool: pool,
wg: wg,
jobChan: make(chan Jober),
quit: make(chan struct{}),
}
}
// worker thread
type worker struct {
pool chan chan Jober
wg *sync.WaitGroup
jobChan chan Jober
quit chan struct{}
}
// start the worker
func (w *worker) Start() {
w.pool <- w.jobChan
go w.dispatcher()
}
func (w *worker) dispatcher() {
for {
select {
case j := <-w.jobChan:
j.Job()
w.pool <- w.jobChan
w.wg.Done()
case <-w.quit:
<-w.pool
close(w.jobChan)
return
}
}
}
// stop the worker
func (w *worker) Stop() {
close(w.quit)
}