forked from egonelbre/async
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasync.go
105 lines (93 loc) · 1.99 KB
/
async.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
package async
import (
"sync"
"sync/atomic"
)
type Result struct {
Done <-chan struct{}
Error <-chan error
}
// All starts all functions concurrently
// if any error occurs it will be sent to the Error channel
// after all functions have terminated the Done channel will get a single value
func All(fns ...func() error) Result {
done := make(chan struct{}, 1)
errs := make(chan error, len(fns))
waiting := int32(len(fns))
for _, fn := range fns {
go func(fn func() error) {
if err := fn(); err != nil {
errs <- err
}
if atomic.AddInt32(&waiting, -1) == 0 {
done <- struct{}{}
close(errs)
close(done)
}
}(fn)
}
if len(fns) == 0 {
done <- struct{}{}
close(errs)
close(done)
}
return Result{done, errs}
}
// Spawns N routines, after each completes runs all whendone functions
func Spawn(N int, fn func(id int), whendone ...func()) {
waiting := int32(N)
for k := 0; k < N; k += 1 {
go func(k int) {
fn(k)
if atomic.AddInt32(&waiting, -1) == 0 {
for _, fn := range whendone {
fn()
}
}
}(int(k))
}
}
// Spawns N routines, iterating over [0..Count) items in increasing order
func Iter(Count int, N int, fn func(i int)) {
var wg sync.WaitGroup
wg.Add(N)
i := int64(0)
for k := 0; k < N; k += 1 {
go func() {
defer wg.Done()
for {
idx := int(atomic.AddInt64(&i, 1) - 1)
if idx >= Count {
break
}
fn(idx)
}
}()
}
wg.Wait()
}
// Spawns N routines, iterating over [0..Count] items by splitting
// them into blocks [start..limit), note that item "limit" shouldn't be
// processed.
func BlockIter(Count int, N int, fn func(start, limit int)) {
var wg sync.WaitGroup
start, left := 0, Count
for k := 0; k < N; k += 1 {
count := (left + (N - k - 1)) / (N - k)
limit := start + count
if limit >= Count {
limit = Count
}
wg.Add(1)
go func(start, limit int) {
defer wg.Done()
fn(start, limit)
}(start, limit)
start = start + count
left -= count
if left <= 0 {
break
}
}
wg.Wait()
}