-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathparallel.go
More file actions
58 lines (53 loc) · 1.52 KB
/
Copy pathparallel.go
File metadata and controls
58 lines (53 loc) · 1.52 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
package cinc
import (
"context"
"sync"
)
// maxParallelTransfers bounds how many cookbook file transfers (pre-signed
// bookshelf uploads/downloads) run concurrently. This work is latency-bound and
// embarrassingly parallel, but fan-out is capped so a large cookbook does not
// open an unbounded number of connections.
const maxParallelTransfers = 8
// parallelForEach runs fn for every item using at most maxParallelTransfers
// concurrent workers. It returns the first error encountered, if any, and
// cancels the context handed to in-flight and not-yet-started work so the whole
// operation fails fast. If the parent context is canceled and no work errored,
// the context's error is returned.
func parallelForEach[T any](ctx context.Context, items []T, fn func(context.Context, T) error) error {
if len(items) == 0 {
return nil
}
ctx, cancel := context.WithCancel(ctx)
defer cancel()
sem := make(chan struct{}, maxParallelTransfers)
var wg sync.WaitGroup
var mu sync.Mutex
var firstErr error
for _, item := range items {
if ctx.Err() != nil {
break // an earlier worker failed (or the parent canceled); stop launching
}
sem <- struct{}{} // block until a worker slot frees up
wg.Add(1)
go func(item T) {
defer wg.Done()
defer func() { <-sem }()
if ctx.Err() != nil {
return
}
if err := fn(ctx, item); err != nil {
mu.Lock()
if firstErr == nil {
firstErr = err
cancel()
}
mu.Unlock()
}
}(item)
}
wg.Wait()
if firstErr != nil {
return firstErr
}
return ctx.Err()
}