-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathworker.go
More file actions
40 lines (34 loc) · 787 Bytes
/
worker.go
File metadata and controls
40 lines (34 loc) · 787 Bytes
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
package workbalancer
import (
"sync"
)
type worker struct {
workloads chan Workload
results chan<- Result
availableWorkers chan<- *worker
wg *sync.WaitGroup
}
func newWorker(availableWorkers chan<- *worker, results chan<- Result, wg *sync.WaitGroup) *worker {
worker := &worker{
workloads: make(chan Workload, 1),
results: results,
availableWorkers: availableWorkers,
wg: wg,
}
go worker.work()
worker.availableWorkers <- worker
return worker
}
func (w *worker) addWork(workload Workload) {
w.workloads <- workload
}
func (w *worker) work() {
for workload := range w.workloads {
w.results <- workload.Do()
w.availableWorkers <- w
}
w.wg.Done()
}
func (w *worker) close() {
close(w.workloads)
}