-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathparallel_map.go
More file actions
72 lines (63 loc) · 1.25 KB
/
parallel_map.go
File metadata and controls
72 lines (63 loc) · 1.25 KB
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 underscore
import (
"context"
"runtime"
"sync"
)
// ParallelMap applies fn to each element of values using a worker pool and preserves order.
// If workers <= 0, it defaults to GOMAXPROCS.
// On error, the first error is returned and processing is canceled; partial results are discarded.
func ParallelMap[T, P any](ctx context.Context, values []T, workers int, fn func(context.Context, T) (P, error)) ([]P, error) {
if workers <= 0 {
workers = runtime.GOMAXPROCS(0)
}
type task struct {
idx int
val T
}
res := make([]P, len(values))
tasks := make(chan task)
ctx, cancel := context.WithCancel(ctx)
defer cancel()
var wg sync.WaitGroup
var once sync.Once
var firstErr error
worker := func() {
defer wg.Done()
for t := range tasks {
select {
case <-ctx.Done():
return
default:
}
v, err := fn(ctx, t.val)
if err != nil {
once.Do(func() {
firstErr = err
cancel()
})
continue
}
res[t.idx] = v
}
}
wg.Add(workers)
for i := 0; i < workers; i++ {
go worker()
}
OUTER:
for i, v := range values {
select {
case <-ctx.Done():
break OUTER
default:
tasks <- task{idx: i, val: v}
}
}
close(tasks)
wg.Wait()
if firstErr != nil {
return nil, firstErr
}
return res, nil
}