-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.go
61 lines (54 loc) · 1.11 KB
/
worker.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
package cyclone
type request struct {
payload interface{}
responseChan chan interface{}
terminate func()
}
func newRequest(payload interface{}) request {
return request{
payload: payload,
responseChan: make(chan interface{}),
terminate: func() {},
}
}
type worker struct {
task Task
requestChan <-chan request
terminationChan chan struct{}
closedChan chan struct{}
}
func newWorker(requestChan <-chan request, task Task) *worker {
w := worker{
requestChan: requestChan,
task: task,
terminationChan: make(chan struct{}),
closedChan: make(chan struct{}),
}
go w.run()
return &w
}
func (w *worker) run() {
defer close(w.closedChan)
for {
select {
case request := <-w.requestChan:
request.terminate = w.terminate
result := w.task.Run(request.payload)
select {
case request.responseChan <- result:
case <-w.terminationChan:
w.task.Terminate()
return
}
case <-w.terminationChan:
w.task.Terminate()
return
}
}
}
func (w *worker) terminate() {
close(w.terminationChan)
}
func (w *worker) wait() {
<-w.closedChan
}