-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparallel_slice_loop.go
More file actions
72 lines (68 loc) · 1.99 KB
/
Copy pathparallel_slice_loop.go
File metadata and controls
72 lines (68 loc) · 1.99 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 gofu
import "sync"
// ForEach calls fn for each element concurrently. [ ReadOnly ] [ time: O(n/p); space: O(1)]
//
// Example:
//
// bigSlice.Parallel(4).ForEach(func(v int) { fmt.Println(v) })
func (ps SliceParallel[T]) ForEach(fn func(T)) {
n := ps.Scale(len(ps.Slice))
ps.ForEachChunk(n, func(_ int, chunk Slice[T]) {
chunk.ForEach(fn)
})
}
// ForEachChunk splits the slice into chunks and runs fn on each chunk in a goroutine. [ ReadOnly ] [ time: O(n/p); space: O(1)]
//
// If chunks ≤ 0, the Scale function determines parallelism.
// Runs sequentially when the scale function returns ≤ 1.
//
// Example:
//
// bigSlice.Parallel(4).ForEachChunk(0, func(i int, chunk gofu.Slice[int]) { ... })
func (ps SliceParallel[T]) ForEachChunk(chunks int, fn func(int, Slice[T])) {
if chunks <= 0 {
chunks = ps.Scale(len(ps.Slice))
}
if chunks <= 1 || len(ps.Slice) < chunks {
fn(0, ps.Slice)
return
}
var wg sync.WaitGroup
ps.Slice.ForEachChunk(chunks, func(i int, chunk Slice[T]) {
wg.Add(1)
go func() {
defer wg.Done()
fn(i, chunk)
}()
})
wg.Wait()
}
// MapChunks splits the slice into chunks, runs fn on each chunk in a goroutine, and returns results in order. [ Immutable ] [ time: O(n/p); space: O(p)]
//
// If chunks ≤ 0, the Scale function determines parallelism.
// Runs sequentially when the scale function returns ≤ 1. Results are ordered by chunk index.
//
// Example:
//
// bigSlice.Parallel(3).MapChunks(0, func(i int, chunk gofu.Slice[int]) []int {
// return chunk.Filter(func(v int) bool { return v > 0 }).Collect()
// })
func (ps SliceParallel[T]) MapChunks[R any](chunks int, fn func(int, Slice[T]) R) []R {
if chunks <= 0 {
chunks = ps.Scale(len(ps.Slice))
}
if chunks <= 1 || len(ps.Slice) < chunks {
return []R{fn(0, ps.Slice)}
}
results := make([]R, chunks)
var wg sync.WaitGroup
ps.Slice.ForEachChunk(chunks, func(i int, chunk Slice[T]) {
wg.Add(1)
go func() {
defer wg.Done()
results[i] = fn(i, chunk)
}()
})
wg.Wait()
return results
}