-
Notifications
You must be signed in to change notification settings - Fork 0
/
pool.go
190 lines (155 loc) · 4.79 KB
/
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
package worker
import (
"fmt"
"sync"
"sync/atomic"
)
// Pool is a generic abstraction for a worker pool
type Pool[R any] struct {
jobs chan JobFunc[R]
results chan jobResult[R]
opts PoolOpts
jobWg sync.WaitGroup
resultsWg sync.WaitGroup
closed bool
launchedRoutines int32
}
type jobResult[R any] struct {
res R
err error
}
// JobFunc is a generic type representing job functions
type JobFunc[R any] func() (R, error)
// ResultFunc is a generic type representing job result callback functions
type ResultFunc[R any] func(R, error) error
// ResultBreakFunc is a generic type representing job result callback functions supporting non-error breaks
type ResultBreakFunc[R any] func(R, error) bool
// NewPool creates a new generic thread pool
func NewPool[R any](opts ...PoolOpts) *Pool[R] {
mergedOpts := mergePoolOpts(opts)
var jobs chan JobFunc[R]
var results chan jobResult[R]
if mergedOpts.BufferSize != nil {
jobs = make(chan JobFunc[R], *mergedOpts.BufferSize)
results = make(chan jobResult[R], *mergedOpts.BufferSize)
} else {
jobs = make(chan JobFunc[R])
results = make(chan jobResult[R])
}
pool := &Pool[R]{
jobs: jobs,
results: results,
opts: mergedOpts,
}
pool.initWorkers()
return pool
}
// Result invokes the provided callback when results are received, and breaks + returns the callback error if non-nil
func (p *Pool[R]) Result(callback ResultFunc[R]) error {
for result := range p.results {
if err := callback(result.res, result.err); err != nil {
return err
}
}
return nil
}
// ResultBreak invokes the provided callback when results are received, and breaks subsequent callbacks if the callback return boolean is true
func (p *Pool[R]) ResultBreak(callback ResultBreakFunc[R]) {
for result := range p.results {
brek := callback(result.res, result.err)
if brek {
break
}
}
}
// SubmitJob queues the job function for execution
func (p *Pool[R]) SubmitJob(job JobFunc[R]) error {
if p.closed {
err := fmt.Errorf("unable to submit job, FinishedJobSubmissions() already called")
logMsg(*p.opts.LogLevel, Error, err.Error())
return err
}
p.jobWg.Add(1)
select {
case p.jobs <- job:
p.jobWg.Done()
default:
// Should we block submissions?
if *p.opts.BlockSubmissions {
err := fmt.Errorf("submit job blocked temporarily, waiting to submit job")
logMsg(*p.opts.LogLevel, Info, err.Error())
p.jobs <- job
p.jobWg.Done()
} else {
// channel is full or blocked, launch new goutine to prevent blocking
maxRoutines := int32(*p.opts.MaxJobGorountines)
// ensure caller doesn't cause goroutine leak
if p.launchedRoutines >= maxRoutines {
err := fmt.Errorf("unable to submit job, number of queued goroutines would excede MaxJobGorountines (%d)", *p.opts.MaxJobGorountines)
logMsg(*p.opts.LogLevel, Error, err.Error())
p.jobWg.Done()
return err
}
atomic.AddInt32(&p.launchedRoutines, 1)
go func() {
p.jobs <- job
p.jobWg.Done()
atomic.AddInt32(&p.launchedRoutines, -1)
}()
}
}
return nil
}
// FinishedJobSubmission informs the pool that no more jobs will be submitted. Attempts to submit additional jobs to the pool, after this function is called, will return an error. Will trigger result callback functions to return after job execution completes.
func (p *Pool[R]) FinishedJobSubmission() {
logMsg(*p.opts.LogLevel, Info, "FinishedJobSubmission called")
p.closed = true
go func() {
// Don't close jobs until all goroutine-queued submissions are sent
p.jobWg.Wait()
close(p.jobs)
}()
go func() {
// Don't close results until all goroutine-queued results are sent
p.resultsWg.Wait()
close(p.results)
}()
}
func (p *Pool[R]) initWorkers() {
for i := 0; i < *p.opts.WorkerCount; i++ {
// Spin up worker goroutine
go func(workerInx int) {
for job := range p.jobs {
p.resultsWg.Add(1)
// Execute job
result, err := job()
select {
case p.results <- jobResult[R]{result, err}:
p.resultsWg.Done()
default:
// channel is full or blocked, launch new goutine to prevent blocking
maxRoutines := int32(*p.opts.MaxJobGorountines)
// ensure caller doesn't cause goroutine leak
if p.launchedRoutines >= maxRoutines {
stallErr := fmt.Sprintf("worker stalled: unable to send job results, number of queued goroutines would excede MaxJobGorountines (%d)", *p.opts.MaxJobGorountines)
logMsg(*p.opts.LogLevel, Error, stallErr)
p.results <- jobResult[R]{
result, err,
}
p.resultsWg.Done()
} else {
atomic.AddInt32(&p.launchedRoutines, 1)
go func() {
p.results <- jobResult[R]{
result, err,
}
p.resultsWg.Done()
atomic.AddInt32(&p.launchedRoutines, -1)
}()
}
}
}
logMsg(*p.opts.LogLevel, Info, "Worker %v finished", workerInx)
}(i)
}
}