-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathworker.go
43 lines (38 loc) · 863 Bytes
/
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
package artifex
// Worker attaches to a provided worker pool, and
// looks for jobs on its job channel
type Worker struct {
workerPool chan chan Job
jobChannel chan Job
quit chan bool
}
// NewWorker creates a new worker using the given id and
// attaches to the provided worker pool. It also initializes
// the job/quit channels
func NewWorker(workerPool chan chan Job) *Worker {
return &Worker{
workerPool: workerPool,
jobChannel: make(chan Job),
quit: make(chan bool),
}
}
// Start initializes a select loop to listen for jobs to execute
func (w Worker) Start() {
go func() {
for {
w.workerPool <- w.jobChannel
select {
case job := <-w.jobChannel:
job.Run()
case <-w.quit:
return
}
}
}()
}
// Stop will end the job select loop for the worker
func (w Worker) Stop() {
go func() {
w.quit <- true
}()
}