-
Notifications
You must be signed in to change notification settings - Fork 2
/
concurrency.go
75 lines (62 loc) · 1.09 KB
/
concurrency.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
package sugar
import "sync"
type synchronize struct {
locker sync.Locker
}
func (s *synchronize) Do(cb func() error) {
s.locker.Lock()
Try(cb)
s.locker.Unlock()
}
func Synchronize(opt ...sync.Locker) synchronize {
if len(opt) > 1 {
panic("unexpected arguments")
} else if len(opt) == 0 {
opt = append(opt, &sync.Mutex{})
}
return synchronize{locker: opt[0]}
}
func Async[A any](f func() A) chan A {
ch := make(chan A)
go func() {
ch <- f()
}()
return ch
}
// FanIn ...
func FanIn(in ...chan any) <-chan any {
out := make(chan any)
for i := range in {
tmp := in[i]
go func() {
out <- tmp
}()
}
return out
}
func FanOut(ch <-chan any, n int) []chan any {
cs := make([]chan any, 0, n)
for i := 0; i < n; i++ {
cs = append(cs, make(chan any))
}
distributeToChannels := func(ch <-chan any, cs []chan any) {
defer func(cs []chan any) {
for _, c := range cs {
close(c)
}
}(cs)
for {
for _, c := range cs {
select {
case val, ok := <-ch:
if !ok {
return
}
c <- val
}
}
}
}
go distributeToChannels(ch, cs)
return cs
}