-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.go
48 lines (44 loc) · 820 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
package workerpool
import (
"log"
"runtime"
"sync/atomic"
//"net/http"
//"io/ioutil"
)
type Worker struct {
Pool *Dispatcher
Index int
WorkerPool chan chan Job
JobChannel chan Job
Quit chan bool
}
func NewWorker(workerPool chan chan Job, i int, p *Dispatcher) Worker {
return Worker{
Pool: p,
Index: i,
WorkerPool: workerPool,
JobChannel: make(chan Job),
Quit: make(chan bool, 1)}
}
func (w Worker) Start() {
go func() {
for {
w.WorkerPool <- w.JobChannel
select {
case job := <-w.JobChannel:
job.Handler(job.Input)
atomic.AddUint64(&(w.Pool.Ops), 1)
runtime.Gosched()
case <-w.Quit:
log.Printf("[workerpool], worker %d stoped.\n", w.Index)
return
}
}
}()
}
func (w Worker) Stop() {
go func() {
w.Quit <- true
}()
}