-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathparallel_reduce.go
More file actions
92 lines (78 loc) · 1.67 KB
/
parallel_reduce.go
File metadata and controls
92 lines (78 loc) · 1.67 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package underscore
import (
"context"
"runtime"
"sync"
)
// ParallelReduce applies a reduction function in parallel using a worker pool.
// The operation must be associative and commutative for correct results.
// If workers <= 0, defaults to GOMAXPROCS.
// On error, the first error is returned and processing is canceled.
//
// Note: Order of operations is not guaranteed, so use only with associative/commutative operations.
func ParallelReduce[T, P any](ctx context.Context, values []T, workers int, fn func(context.Context, T, P) (P, error), acc P) (P, error) {
if workers <= 0 {
workers = runtime.GOMAXPROCS(0)
}
if len(values) == 0 {
return acc, nil
}
type task struct {
idx int
val T
}
tasks := make(chan task)
results := make(chan P, len(values))
ctx, cancel := context.WithCancel(ctx)
defer cancel()
var wg sync.WaitGroup
var once sync.Once
var firstErr error
// Workers
wg.Add(workers)
for i := 0; i < workers; i++ {
go func() {
defer wg.Done()
for t := range tasks {
select {
case <-ctx.Done():
return
default:
}
result, err := fn(ctx, t.val, acc)
if err != nil {
once.Do(func() {
firstErr = err
cancel()
})
return
}
results <- result
}
}()
}
// Send tasks
go func() {
for i, v := range values {
select {
case <-ctx.Done():
close(tasks)
return
default:
tasks <- task{idx: i, val: v}
}
}
close(tasks)
}()
wg.Wait()
close(results)
if firstErr != nil {
return acc, firstErr
}
// Combine results
for result := range results {
// This is a simplified combination - in practice, you'd need a combiner function
acc = result
}
return acc, nil
}