-
Notifications
You must be signed in to change notification settings - Fork 1
/
pond.go
72 lines (54 loc) · 1.36 KB
/
pond.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
package koi
import (
"errors"
"golang.org/x/sync/semaphore"
)
var (
errWorkerNotFound = errors.New("worker Not Found")
errMinConcurrentCount = errors.New("concurrent count must be at least 1")
errNegativeQueueSize = errors.New("worker request queue size can not be negative")
)
type Pond struct {
Workers map[string]innerWorker
}
func NewPond() *Pond {
return &Pond{
Workers: make(map[string]innerWorker),
}
}
func (p *Pond) RegisterWorker(id string, worker Worker) error {
if err := worker.Validate(); err != nil {
return err
}
innerWorker := innerWorker{
Worker: worker,
ResultChan: make(chan any, worker.QueueSize),
RequestChan: make(chan any, worker.QueueSize),
Semaphore: semaphore.NewWeighted(worker.ConcurrentCount),
}
go p.manageWorker(innerWorker)
p.Workers[id] = innerWorker
return nil
}
func (p *Pond) AddWork(workerID string, request any) (chan any, error) {
worker, ok := p.Workers[workerID]
if !ok {
return nil, errWorkerNotFound
}
// add request to worker queue
worker.RequestChan <- request
return worker.ResultChan, nil
}
func (p Pond) ResultChan(workerID string) chan any {
worker, ok := p.Workers[workerID]
if ok {
return worker.ResultChan
}
return nil
}
func (p *Pond) manageWorker(worker innerWorker) {
for request := range worker.RequestChan {
worker.Acquire()
go worker.work(request)
}
}