-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdispatcher.go
49 lines (42 loc) · 995 Bytes
/
dispatcher.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 dispatcher
import (
"log"
)
type Dispatcher struct {
// A pool of workers channels that are registered with the dispatcher
WorkerPool chan chan Job
MaxWorkers int
JobQueue chan Job
}
func NewDispatcher(maxWorkers int, maxQueue int) *Dispatcher {
pool := make(chan chan Job, maxWorkers)
return &Dispatcher{
WorkerPool: pool,
MaxWorkers: maxWorkers,
JobQueue: NewJobQueue(maxQueue),
}
}
func (d *Dispatcher) Run() {
// starting n number of workers
for i := 0; i < d.MaxWorkers; i++ {
worker := NewWorker(d.WorkerPool)
worker.Start()
}
go d.dispatch()
}
func (d *Dispatcher) dispatch() {
for {
select {
case job := <-d.JobQueue:
// a job request has been received
go func(job Job) {
log.Println("received job")
// try to obtain a worker job channel that is available.
// this will block until a worker is idle
jobChannel := <-d.WorkerPool
// dispatch the job to the worker job channel
jobChannel <- job
}(job)
}
}
}