-
Notifications
You must be signed in to change notification settings - Fork 1
/
worker.go
92 lines (78 loc) · 2.13 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
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
package asyncexecutor
import (
"fmt"
"sync"
)
type Worker struct {
id int
globalJobQueue chan *Job
GlobalResponseQueue chan *ResponseObject
jobQueue chan *Job
responseQueue chan *ResponseObject
responseHandler ResponseHandler
responseHandlerEnabled bool
}
func NewWorker(workerID int, globalJobQueue chan *Job, GlobalResponseQueue chan *ResponseObject) *Worker {
return &Worker{
workerID,
globalJobQueue,
GlobalResponseQueue,
make(chan *Job, 10),
make(chan *ResponseObject, 10),
&CleaningHandler{},
true}
}
func (worker *Worker) SetResponseHandler(handler ResponseHandler) {
worker.responseHandler = handler
}
func (worker *Worker) start(wg *sync.WaitGroup) {
defer wg.Done()
fmt.Printf("Started worker [id = %v] \n", worker.id)
for {
select {
case job, ok := <-worker.globalJobQueue:
if !ok {
return
}
response := job.call()
// Check if the global response queue is full and remove elements to prevent deadlock.
// When adding jobs if there is no consumer to remove the result the CreateJob function will block and produce a deadlock.
if worker.responseHandlerEnabled == true {
if cap(worker.GlobalResponseQueue)-len(worker.GlobalResponseQueue) == 1 {
worker.responseHandler.Handle(<-worker.GlobalResponseQueue)
}
}
worker.GlobalResponseQueue <- response
case job, ok := <-worker.jobQueue:
if !ok {
return
}
response := job.call()
if worker.responseHandlerEnabled == true {
if cap(worker.responseQueue)-len(worker.responseQueue) == 1 {
worker.responseHandler.Handle(<-worker.responseQueue)
}
}
worker.responseQueue <- response
}
}
}
func (worker *Worker) stop() {
fmt.Printf("Stopping worker [id = %v] \n", worker.id)
if worker.responseHandlerEnabled == true {
loop:
for {
select {
case response, ok := <-worker.GlobalResponseQueue:
if ok {
worker.responseHandler.Handle(response)
} else {
break
}
default:
break loop
}
}
}
close(worker.jobQueue)
}