/
worker.go
49 lines (42 loc) · 974 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
44
45
46
47
48
49
package workerqueue
// Worker struct holds the information regarding the worker
type Worker struct {
ID int
JobChannel chan Job
WorkerPool chan chan Job
QuitChan chan bool
}
// NewWorker method will create a worker object and return it
func NewWorker(id int, workerPool chan chan Job) *Worker {
worker := &Worker{
ID: id,
JobChannel: make(chan Job),
WorkerPool: workerPool,
QuitChan: make(chan bool)}
return worker
}
func (w *Worker) startWorker() {
for {
// Add ourselves to the work queue
w.WorkerPool <- w.JobChannel
select {
case work := <-w.JobChannel:
// Receive a work request
work.Process()
case <-w.QuitChan:
// We have been asked to stop the processing
return
}
}
}
// Start method will start the worker
func (w *Worker) Start() {
go w.startWorker()
}
// Stop method will stop the worker
func (w *Worker) Stop() {
go func() {
// Send a stop request in quit channel
w.QuitChan <- true
}()
}