-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathiterator.go
More file actions
47 lines (39 loc) · 940 Bytes
/
iterator.go
File metadata and controls
47 lines (39 loc) · 940 Bytes
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
package patron
import (
"runtime"
"sync"
"sync/atomic"
)
// ForEach executes the given function f for each element in the items slice concurrently.
// It automatically determines the optimal number of workers based on GOMAXPROCS.
// This provides a lightweight alternative to the WorkerOrchestrator for simple iteration tasks.
func ForEach[T any](items []T, f func(item T)) {
numWorkers := runtime.GOMAXPROCS(0)
numItems := len(items)
// If fewer items than workers, reduce worker count to match items
if numItems < numWorkers {
numWorkers = numItems
}
if numWorkers == 0 {
return
}
var idx atomic.Int64
var wg sync.WaitGroup
// Task closure to be executed by workers
task := func() {
defer wg.Done()
for {
// Get next index atomically
i := int(idx.Add(1) - 1)
if i >= numItems {
return
}
f(items[i])
}
}
wg.Add(numWorkers)
for i := 0; i < numWorkers; i++ {
go task()
}
wg.Wait()
}