-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.go
49 lines (41 loc) · 901 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 ramix
import "context"
type worker struct {
id int
tasks chan *Context
ctx context.Context
cancel context.CancelFunc
}
func (w *worker) start() {
go func() {
for {
select {
// if server use worker pool, this context is the server's context
// else, this context is the connection's context
case <-w.ctx.Done():
debug("Worker %d stopped", w.id)
return
case ctx := <-w.tasks:
// If the context is nil, it means the worker is stopped
if ctx == nil {
debug("Worker %d stopped", w.id)
return
}
ctx.Next()
}
}
}()
debug("Worker %d started", w.id)
}
func (w *worker) stop() {
w.cancel()
close(w.tasks)
}
func newWorker(workerID int, maxTasksCount uint32) *worker {
w := &worker{
id: workerID,
tasks: make(chan *Context, maxTasksCount),
}
w.ctx, w.cancel = context.WithCancel(context.Background())
return w
}