|
| 1 | +--- |
| 2 | +title: "ParallelReduce" |
| 3 | +date: 2025-01-16T00:00:00-00:00 |
| 4 | +--- |
| 5 | + |
| 6 | +`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. |
| 7 | + |
| 8 | +**Note:** This is an experimental function. Order of operations is not guaranteed, so use only with associative and commutative operations (like addition, multiplication, min, max). |
| 9 | + |
| 10 | +```go |
| 11 | +package main |
| 12 | + |
| 13 | +import ( |
| 14 | + "context" |
| 15 | + "fmt" |
| 16 | + "time" |
| 17 | + u "github.com/rjNemo/underscore" |
| 18 | +) |
| 19 | + |
| 20 | +func main() { |
| 21 | + nums := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} |
| 22 | + ctx := context.Background() |
| 23 | + |
| 24 | + // Parallel sum (safe - addition is associative and commutative) |
| 25 | + result, err := u.ParallelReduce(ctx, nums, 4, func(ctx context.Context, n int, acc int) (int, error) { |
| 26 | + // Simulate expensive computation |
| 27 | + time.Sleep(10 * time.Millisecond) |
| 28 | + return n + acc, nil |
| 29 | + }, 0) |
| 30 | + |
| 31 | + if err != nil { |
| 32 | + panic(err) |
| 33 | + } |
| 34 | + fmt.Println(result) // Result will vary due to parallel execution |
| 35 | + |
| 36 | + // With context cancellation |
| 37 | + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) |
| 38 | + defer cancel() |
| 39 | + |
| 40 | + _, err = u.ParallelReduce(ctx, nums, 4, func(ctx context.Context, n int, acc int) (int, error) { |
| 41 | + time.Sleep(100 * time.Millisecond) |
| 42 | + return n + acc, nil |
| 43 | + }, 0) |
| 44 | + |
| 45 | + if err != nil { |
| 46 | + fmt.Println("Operation was cancelled:", err) |
| 47 | + } |
| 48 | +} |
| 49 | +``` |
| 50 | + |
| 51 | +**Warning:** Do not use ParallelReduce for non-associative operations like subtraction or division, as the results will be unpredictable due to parallel execution order. |
0 commit comments