-
Notifications
You must be signed in to change notification settings - Fork 2
/
workbalancer.go
58 lines (50 loc) · 1.14 KB
/
workbalancer.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
package workbalancer
import (
"sync"
)
type WorkBalancer interface {
Balance(workloads []Workload)
GetResults() <-chan Result
}
type channelBalancer struct {
availableWorkers chan *worker
results chan Result
workers []*worker
wg *sync.WaitGroup
}
func NewChannelBalancer(nWorkers int) WorkBalancer {
availableWorkers := make(chan *worker, nWorkers)
results := make(chan Result, nWorkers)
var workers []*worker
wg := &sync.WaitGroup{}
wg.Add(nWorkers)
for i := 0; i < nWorkers; i++ {
worker := newWorker(availableWorkers, results, wg)
workers = append(workers, worker)
}
return &channelBalancer{
availableWorkers: availableWorkers,
results: results,
workers: workers,
wg: wg,
}
}
type Workload interface {
Do() Result
}
type Result interface {
}
func (b *channelBalancer) Balance(workloads []Workload) {
for _, workload := range workloads {
worker := <-b.availableWorkers
worker.addWork(workload)
}
for _, worker := range b.workers {
worker.close()
}
b.wg.Wait()
close(b.results)
}
func (b *channelBalancer) GetResults() <-chan Result {
return b.results
}