/
map.go
261 lines (222 loc) · 5.07 KB
/
map.go
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
// Package parallel provides higher-order functions that run in parallel.
// Maximum concurrency may be restricted for all the functions.
//
// Context cancellation: If the input context is canceled, MapBounded* will
// immediately stop mapping any new items, wait for workers running to exit,
// then return the context error.
package parallel
import (
"context"
"fmt"
"sync"
"sync/atomic"
"go.lepak.sg/playground/chops"
"golang.org/x/sync/errgroup"
"golang.org/x/sync/semaphore"
)
const debug = true
// MapBoundedSema maps a list of ~[]T to []R using a provided map function f.
// It does this in parallel with a maximum of inflight workers.
func MapBoundedSema[S ~[]T, T, R any](
ctx context.Context, list S, f func(int, T) R, inflight int,
) (result []R, err error) {
result = make([]R, len(list))
sema := semaphore.NewWeighted(int64(inflight))
for i, v := range list {
err = sema.Acquire(ctx, 1)
if err != nil {
// ctx was canceled
break
}
go func(i int, v T) {
defer sema.Release(1)
result[i] = f(i, v)
}(i, v)
}
if err == nil {
// possible that the context is canceled after we started
// the last workerbut before we acquired the entire semaphore
err = sema.Acquire(ctx, int64(inflight))
if err == nil {
// context is not canceled, this is the happy path
return
}
}
// context is already canceled, this will eventually acquire
for sema.Acquire(ctx, int64(inflight)) != nil {
}
return
}
// MapBoundedPool maps a list of ~[]T to []R using a provided map function f.
// It does this in parallel with a fixed-size pool of workers.
func MapBoundedPool[S ~[]T, T, R any](
ctx context.Context, list S, f func(int, T) R, workers int,
) (result []R, err error) {
result = make([]R, len(list))
indices := make(chan int, workers)
var wg sync.WaitGroup
var wstat []int
if debug {
wstat = make([]int, len(list))
}
for i := 0; i < workers; i++ {
wg.Add(1)
i := i
go func() {
defer wg.Done()
for {
select {
case <-ctx.Done():
return
case j, ok := <-indices:
if !ok {
return
}
if debug {
wstat[j] = i
}
result[j] = f(j, list[j])
}
}
}()
}
producer:
for i := range list {
select {
case <-ctx.Done():
err = ctx.Err()
break producer
case indices <- i:
}
}
close(indices)
wg.Wait()
if debug {
fmt.Println(wstat)
}
return
}
// MapBoundedPoolLockfree maps a list of ~[]T to []R using a
// provided map function f.
// It does this in parallel with a fixed-size pool of workers.
// No channels or locks are involved in the dispatch process.
func MapBoundedPoolLockfree[S ~[]T, T, R any](
ctx context.Context, list S, f func(int, T) R, workers int,
) (result []R, err error) {
result = make([]R, len(list))
var next int64
var wg sync.WaitGroup
var wstat []int
if debug {
wstat = make([]int, len(list))
}
for i := 0; i < workers; i++ {
wg.Add(1)
i := i
go func() {
defer wg.Done()
for {
currI64 := atomic.LoadInt64(&next)
if currI64 == int64(len(list)) {
return
}
if !atomic.CompareAndSwapInt64(&next, currI64, currI64+1) {
continue
}
curr := int(currI64)
if debug {
wstat[curr] = i
}
result[curr] = f(curr, list[curr])
}
}()
}
select {
case <-ctx.Done():
atomic.StoreInt64(&next, int64(len(list)))
err = ctx.Err()
// still need to wait for everyone to exit
wg.Wait()
case <-chops.Wait(&wg):
}
if debug {
fmt.Println(wstat)
}
return
}
// MapBoundedErrgroup maps a list of ~[]T to []R
// using a provided map function f.
// It does this in parallel with a maximum of inflight workers.
// An errgroup.Group is used to coordinate them.
func MapBoundedErrgroup[S ~[]T, T, R any](
ctx context.Context, list S, f func(int, T) R, workers int,
) (result []R, err error) {
result = make([]R, len(list))
g, ctx := errgroup.WithContext(ctx)
g.SetLimit(workers)
for i := range list {
i := i
if ctx.Err() != nil {
break
}
g.Go(func() error {
result[i] = f(i, list[i])
return ctx.Err()
})
}
// err = g.Wait()
// if err == nil {
// return result, nil
// } else {
// return nil, err
// }
return result, g.Wait()
}
// MapBoundedPoolErrgroup maps a list of ~[]T to []R
// using a provided map function f.
// It does this in parallel with a fixed-size pool of workers.
// An errgroup.Group is used to coordinate them.
func MapBoundedPoolErrgroup[S ~[]T, T, R any](
ctx context.Context, list S, f func(int, T) R, workers int,
) (result []R, err error) {
result = make([]R, len(list))
indices := make(chan int)
var wstat []int
if debug {
wstat = make([]int, len(list))
}
g, ctx := errgroup.WithContext(ctx)
for i := 0; i < workers; i++ {
i := i
g.Go(func() error {
for {
select {
case j, ok := <-indices:
if !ok {
return nil
}
if debug {
wstat[j] = i
}
result[j] = f(j, list[j])
case <-ctx.Done():
return ctx.Err()
}
}
})
}
producer:
for i := range list {
select {
case <-ctx.Done():
break producer
case indices <- i:
}
}
close(indices)
err = g.Wait()
if debug {
fmt.Println(wstat)
}
return
}