-
Notifications
You must be signed in to change notification settings - Fork 2k
/
worker_pool.go
74 lines (61 loc) · 1.32 KB
/
worker_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
65
66
67
68
69
70
71
72
73
74
// Copyright (c) The Thanos Authors.
// Licensed under the Apache License 2.0.
package pool
import (
"context"
"sync"
)
// Work is a unit of item to be worked on, like Java Runnable.
type Work func()
// WorkerPool is a pool of goroutines that are reusable, similar to Java ThreadPool.
type WorkerPool interface {
// Init initializes the worker pool.
Init()
// Go waits until the next worker becomes available and executes the given work.
Go(work Work)
// Close cancels all workers and waits for them to finish.
Close()
// Size returns the number of workers in the pool.
Size() int
}
type workerPool struct {
sync.Once
ctx context.Context
workCh chan Work
cancel context.CancelFunc
}
func NewWorkerPool(workers uint) WorkerPool {
ctx, cancel := context.WithCancel(context.Background())
return &workerPool{
ctx: ctx,
cancel: cancel,
workCh: make(chan Work, workers),
}
}
func (p *workerPool) Init() {
p.Do(func() {
for i := 0; i < p.Size(); i++ {
go func() {
for {
select {
case <-p.ctx.Done():
// TODO: exhaust workCh before exit
return
case work := <-p.workCh:
work()
}
}
}()
}
})
}
func (p *workerPool) Go(work Work) {
p.Init()
p.workCh <- work
}
func (p *workerPool) Close() {
p.cancel()
}
func (p *workerPool) Size() int {
return cap(p.workCh)
}