-
Notifications
You must be signed in to change notification settings - Fork 18
/
async_slice.go
327 lines (283 loc) · 7.08 KB
/
async_slice.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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
package slices
import (
"context"
"sync"
)
// AllAsync returns true if f returns true for all elements in items.
//
// This is an asynchronous function. It will spawn as many goroutines as you specify
// in the `workers` argument. Set it to zero to spawn a new goroutine for each item.
func AllAsync[S ~[]T, T any](items S, workers int, f func(el T) bool) bool {
if len(items) == 0 {
return true
}
wg := sync.WaitGroup{}
worker := func(jobs <-chan int, result chan<- bool, ctx context.Context) {
defer wg.Done()
for {
select {
case <-ctx.Done():
return
case index, ok := <-jobs:
if !ok {
return
}
if !f(items[index]) {
result <- false
return
}
}
}
}
ctx, cancel := context.WithCancel(context.Background())
// when we're returning the result, cancel all workers
defer cancel()
// calculate workers count
if workers <= 0 || workers > len(items) {
workers = len(items)
}
// run workers
jobs := make(chan int, len(items))
result := make(chan bool, workers)
wg.Add(workers)
for i := 0; i < workers; i++ {
go worker(jobs, result, ctx)
}
// close the result channel when all workers have done
go func() {
wg.Wait()
close(result)
}()
// schedule the jobs: indices to check
for i := 0; i < len(items); i++ {
jobs <- i
}
close(jobs)
for range result {
return false
}
return true
}
// AnyAsync returns true if f returns true for any element in items.
//
// This is an asynchronous function. It will spawn as many goroutines as you specify
// in the `workers` argument. Set it to zero to spawn a new goroutine for each item.
func AnyAsync[S ~[]T, T any](items S, workers int, f func(el T) bool) bool {
if len(items) == 0 {
return false
}
wg := sync.WaitGroup{}
worker := func(jobs <-chan int, result chan<- bool, ctx context.Context) {
defer wg.Done()
for {
select {
case <-ctx.Done():
return
case index, ok := <-jobs:
if !ok {
return
}
if f(items[index]) {
result <- true
return
}
}
}
}
ctx, cancel := context.WithCancel(context.Background())
// when we're returning the result, cancel all workers
defer cancel()
// calculate workers count
if workers <= 0 || workers > len(items) {
workers = len(items)
}
// run workers
jobs := make(chan int, len(items))
result := make(chan bool, workers)
wg.Add(workers)
for i := 0; i < workers; i++ {
go worker(jobs, result, ctx)
}
// close the result channel when all workers have done
go func() {
wg.Wait()
close(result)
}()
// schedule the jobs: indices to check
for i := 0; i < len(items); i++ {
jobs <- i
}
close(jobs)
for range result {
return true
}
return false
}
// EachAsync calls f for each element in items.
//
// This is an asynchronous function. It will spawn as many goroutines as you specify
// in the `workers` argument. Set it to zero to spawn a new goroutine for each item.
func EachAsync[S ~[]T, T any](items S, workers int, f func(el T)) {
wg := sync.WaitGroup{}
worker := func(jobs <-chan int) {
defer wg.Done()
for index := range jobs {
f(items[index])
}
}
// calculate workers count
if workers <= 0 || workers > len(items) {
workers = len(items)
}
// run workers
jobs := make(chan int, len(items))
wg.Add(workers)
for i := 0; i < workers; i++ {
go worker(jobs)
}
// add indices into jobs for workers
for i := 0; i < len(items); i++ {
jobs <- i
}
close(jobs)
wg.Wait()
}
// FilterAsync returns a slice containing only items where f returns true
//
// This is an asynchronous function. It will spawn as many goroutines as you specify
// in the `workers` argument. Set it to zero to spawn a new goroutine for each item.
//
// The resulting items have the same order as in the input slice.
func FilterAsync[S ~[]T, T any](items S, workers int, f func(el T) bool) S {
resultMap := make([]bool, len(items))
wg := sync.WaitGroup{}
worker := func(jobs <-chan int) {
for index := range jobs {
if f(items[index]) {
resultMap[index] = true
}
}
wg.Done()
}
// calculate workers count
if workers <= 0 || workers > len(items) {
workers = len(items)
}
// run workers
jobs := make(chan int, len(items))
wg.Add(workers)
for i := 0; i < workers; i++ {
go worker(jobs)
}
// add indices into jobs for workers
for i := 0; i < len(items); i++ {
jobs <- i
}
close(jobs)
wg.Wait()
// return filtered results
result := make([]T, 0, len(items))
for i, el := range items {
if resultMap[i] {
result = append(result, el)
}
}
return result
}
// MapAsync applies f to all elements in items and returns a slice of the results.
//
// This is an asynchronous function. It will spawn as many goroutines as you specify
// in the `workers` argument. Set it to zero to spawn a new goroutine for each item.
//
// The result items have the same order as in the input slice.
func MapAsync[S ~[]T, T any, G any](items S, workers int, f func(el T) G) []G {
result := make([]G, len(items))
wg := sync.WaitGroup{}
worker := func(jobs <-chan int) {
for index := range jobs {
result[index] = f(items[index])
}
wg.Done()
}
// calculate workers count
if workers <= 0 || workers > len(items) {
workers = len(items)
}
// run workers
jobs := make(chan int, len(items))
wg.Add(workers)
for i := 0; i < workers; i++ {
go worker(jobs)
}
// add indices into jobs for workers
for i := 0; i < len(items); i++ {
jobs <- i
}
close(jobs)
wg.Wait()
return result
}
// ReduceAsync reduces items to a single value with f.
//
// This is an asynchronous function. It will spawn as many goroutines as you specify
// in the `workers` argument. Set it to zero to spawn a new goroutine for each item.
//
// The function is guaranteed to be called with neighbored items. However, it may be called
// out of order. The results are collected into a new slice which is reduced again, until
// only one item remains. You can think about it as a piramid. On each iteration,
// 2 elements ar taken and merged together until only one remains.
//
// An example for sum:
//
// 1 2 3 4 5
// 3 7 5
// 10 5
// 15
func ReduceAsync[S ~[]T, T any](items S, workers int, f func(left T, right T) T) T {
if len(items) == 0 {
var tmp T
return tmp
}
state := make([]T, len(items))
copy(state, items)
wg := sync.WaitGroup{}
worker := func(jobs <-chan int, result chan<- T) {
for index := range jobs {
result <- f(state[index], state[index+1])
}
wg.Done()
}
for len(state) > 1 {
// calculate workers count
if workers <= 0 || workers > len(state) {
workers = len(state)
}
// run workers
jobs := make(chan int, len(state))
wg.Add(workers)
result := make(chan T)
for i := 0; i < workers; i++ {
go worker(jobs, result)
}
go func() {
wg.Wait()
close(result)
}()
// add indices into jobs for workers
for i := 0; i < len(state)-1; i += 2 {
jobs <- i
}
close(jobs)
// collect new state
newState := make([]T, 0, len(state)/2+len(state)%2)
for el := range result {
newState = append(newState, el)
}
if len(state)%2 == 1 {
newState = append(newState, state[len(state)-1])
}
// put new state as current state after all
state = newState
}
return state[0]
}