-
Notifications
You must be signed in to change notification settings - Fork 1
/
concurrent.go
80 lines (64 loc) · 1.16 KB
/
concurrent.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
package enu
import (
"sync"
)
func Async[T any](fn func(chan (T))) chan T {
result := make(chan (T))
go func() {
defer close(result)
fn(result)
}()
return result
}
func Repeat[T any](bufferSize, repeatCount int, fn func(int) T) chan (T) {
ch := make(chan (T), bufferSize)
wg := new(sync.WaitGroup)
for i := 0; i < repeatCount; i++ {
wg.Add(1)
go func(j int) {
defer wg.Done()
ch <- fn(j)
}(i)
}
go func() {
wg.Wait()
close(ch)
}()
return ch
}
func Parallel[T any](bufferSize int, funcs ...func() T) chan (T) {
ch := make(chan (T), bufferSize)
wg := new(sync.WaitGroup)
for _, fn := range funcs {
wg.Add(1)
go func(f func() T) {
defer wg.Done()
ch <- f()
}(fn)
}
go func() {
wg.Wait()
close(ch)
}()
return ch
}
func Retry[T any](bufferSize, maxRetry int, fn func(int) (T, error)) chan (Tuple2[T, error]) {
ch := make(chan (Tuple2[T, error]), bufferSize)
go func() {
defer close(ch)
retry := 0
for {
v, err := fn(retry)
if err == nil {
ch <- Tuple2[T, error]{v, nil}
break
}
if maxRetry < retry {
ch <- Tuple2[T, error]{empty[T](), err}
break
}
retry++
}
}()
return ch
}