-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue.go
82 lines (70 loc) · 1.38 KB
/
queue.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package postmark
type task struct {
Message *Message
}
var taskQueue = make(chan task, 100)
// Dispatcher is a worker queue
type Dispatcher struct {
workerPool chan chan task
Client *Client
}
// NewDispatcher creates a new dispater with workers
func NewDispatcher(maxworkers int, client *Client) *Dispatcher {
pool := make(chan chan task, maxworkers)
return &Dispatcher{pool, client}
}
// Add adds a new task to the queue
func (d *Dispatcher) Add(m *Message) {
taskQueue <- task{m}
}
// Run starts the dispatcher
func (d *Dispatcher) Run() {
for i := 0; i < cap(d.workerPool); i++ {
worker := newWorker(i, d.workerPool, d.Client)
worker.Start()
}
go d.dispatch()
}
func (d *Dispatcher) dispatch() {
for {
select {
case ts := <-taskQueue:
go func(t task) {
taskChannel := <-d.workerPool
taskChannel <- t
}(ts)
}
}
}
type worker struct {
ID int
Client *Client
workerPool chan chan task
quit chan bool
}
func newWorker(id int, wq chan chan task, client *Client) worker {
return worker{
ID: id,
workerPool: wq,
Client: client,
quit: make(chan bool),
}
}
func (w worker) Start() {
go func() {
for {
w.workerPool <- taskQueue
select {
case task := <-taskQueue:
w.Client.SendMessage(task.Message)
case <-w.quit:
return
}
}
}()
}
func (w worker) Stop() {
go func() {
w.quit <- true
}()
}