-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
taskpool.go
55 lines (51 loc) · 1.29 KB
/
taskpool.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
package flowmatic
import (
"runtime"
"sync"
)
// Result is the type returned by the output channel of TaskPool.
type Result[Input, Output any] struct {
In Input
Out Output
Err error
Panic any
}
// TaskPool starts numWorkers workers (or GOMAXPROCS workers if numWorkers < 1) which consume
// the in channel, execute task, and send the Result on the out channel.
// Callers should close the in channel to stop the workers from waiting for tasks.
// The out channel will be closed once the last result has been sent.
func TaskPool[Input, Output any](numWorkers int, task Task[Input, Output]) (in chan<- Input, out <-chan Result[Input, Output]) {
if numWorkers < 1 {
numWorkers = runtime.GOMAXPROCS(0)
}
inch := make(chan Input)
ouch := make(chan Result[Input, Output], numWorkers)
var wg sync.WaitGroup
wg.Add(numWorkers)
for i := 0; i < numWorkers; i++ {
go func() {
defer wg.Done()
for inval := range inch {
func() {
defer func() {
pval := recover()
if pval == nil {
return
}
ouch <- Result[Input, Output]{
In: inval,
Panic: pval,
}
}()
outval, err := task(inval)
ouch <- Result[Input, Output]{inval, outval, err, nil}
}()
}
}()
}
go func() {
wg.Wait()
close(ouch)
}()
return inch, ouch
}