-
Notifications
You must be signed in to change notification settings - Fork 0
/
workers_pool.go
64 lines (57 loc) · 1.44 KB
/
workers_pool.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
package gobulk
import (
"sync/atomic"
)
// newWorkersPool creates a new workerPool instance.
func newWorkersPool(
read func(container *Container) (map[string][]byte, error),
requests chan *workerRequest,
results chan *workerResponse,
workersCount int,
) *workersPool {
p := &workersPool{
read: read,
requests: requests,
results: results,
stop: make(chan struct{}),
}
for i := 0; i < workersCount; i++ {
p.AddWorker()
}
return p
}
// workersPool is a simple workers pool with ability to vary the workers number.
type workersPool struct {
read func(container *Container) (map[string][]byte, error)
requests chan *workerRequest
results chan *workerResponse
stop chan struct{}
workersCount int64
}
// AddWorker runs a new worker instance.
func (p *workersPool) AddWorker() {
w := worker{
read: p.read,
requests: p.requests,
results: p.results,
stop: p.stop,
}
atomic.AddInt64(&p.workersCount, 1)
go w.run()
}
// StopWorker stops the first free worker instance.
func (p *workersPool) StopWorker() {
if atomic.LoadInt64(&p.workersCount) > 0 {
atomic.AddInt64(&p.workersCount, -1)
p.stop <- struct{}{}
}
}
// WorkersCount returns the number of currently running workers.
func (p *workersPool) WorkersCount() int64 {
return atomic.LoadInt64(&p.workersCount)
}
// Stop stops the pool and all its workers.
func (p *workersPool) Stop() {
atomic.StoreInt64(&p.workersCount, 0)
close(p.stop)
}