-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.go
65 lines (56 loc) · 1015 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package workerpool
import (
"context"
)
type Worker struct {
pool *WorkerPool
done chan struct{}
}
func NewWorker(pool *WorkerPool) *Worker {
return &Worker{
pool: pool,
done: make(chan struct{}),
}
}
func (w *Worker) Start() {
go func() {
for {
select {
case <-w.pool.ctx.Done():
return
case task := <-w.pool.Tasks:
w.execute(task)
case <-w.done:
// we have received a signal to stop
return
}
}
}()
}
// Stop signals the worker to stop listening for work requests.
func (w *Worker) Stop() {
go func() {
w.done <- struct{}{}
}()
}
func (w *Worker) execute(task Task) {
ctx := w.pool.ctx
if w.pool.timeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(w.pool.ctx, w.pool.timeout)
defer cancel()
}
done := make(chan struct{})
go func() {
task(ctx)
close(done)
}()
select {
case <-done:
// The task finished successfully
return
case <-ctx.Done():
// The context timed out, the task took too long
return
}
}