-
Notifications
You must be signed in to change notification settings - Fork 3
/
worker.go
56 lines (49 loc) · 1.18 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
package main
import (
"fmt"
)
// NewWorker creates, and returns a new Worker object. Its only argument
// is a channel that the worker can add itself to whenever it is done its
// work.
func NewWorker(id int, workerQueue chan chan WorkRequest) Worker {
// Create, and return the worker.
worker := Worker{
ID: id,
Work: make(chan WorkRequest),
WorkerPool: workerQueue,
QuitChan: make(chan bool)}
return worker
}
type Worker struct {
ID int
Work chan WorkRequest
WorkerPool chan chan WorkRequest
QuitChan chan bool
}
// This function "starts" the worker by starting a goroutine, that is
// an infinite "for-select" loop.
func (w Worker) Start() {
go func() {
for {
// Add ourselves into the worker queue.
w.WorkerPool <- w.Work
select {
case work := <-w.Work:
// Receive a work request.
work.Execute(nil)
case <-w.QuitChan:
// We have been asked to stop.
fmt.Printf("worker%d stopping\n", w.ID)
return
}
}
}()
}
// Stop tells the worker to stop listening for work requests.
//
// Note that the worker will only stop *after* it has finished its work.
func (w Worker) Stop() {
go func() {
w.QuitChan <- true
}()
}