-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoConcurrent.go
112 lines (101 loc) · 1.88 KB
/
goConcurrent.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
package GoConcurrent
import "sync"
// Or
func Or(channels ...<-chan interface{}) <-chan interface{} {
switch len(channels) {
case 0:
return nil
case 1:
return channels[0]
}
orDone := make(chan interface{})
go func() {
defer close(orDone)
switch len(channels) {
case 2:
select {
case <-channels[0]:
case <-channels[1]:
}
default:
select {
case <-channels[0]:
case <-channels[1]:
case <-channels[2]:
case <-Or(append(channels[3:], orDone)...):
}
}
}()
return orDone
}
// Repeat
func Repeat(done <-chan interface{}, values ...interface{}) <-chan interface{} {
valStream := make(chan interface{})
go func() {
defer close(valStream)
for {
for _, v := range values {
select {
case <-done:
return
case valStream <- v:
}
}
}
}()
return valStream
}
// RepeatFn
func RepeatFn(done <-chan interface{}, fn func() interface{}) <-chan interface{} {
valStream := make(chan interface{})
go func() {
defer close(valStream)
for {
select {
case <-done:
return
case valStream <- fn():
}
}
}()
return valStream
}
// Take
func Take(done <-chan interface{}, valStream <-chan interface{}, num int) <-chan interface{} {
takeStream := make(chan interface{})
go func() {
defer close(takeStream)
for i := 0; i < num; i++ {
select {
case <-done:
return
case takeStream <- <-valStream:
}
}
}()
return takeStream
}
// FanIn
func FanIn(done <-chan interface{}, channels ...<-chan interface{}) <-chan interface{} {
var wg sync.WaitGroup
multiPlexedStream := make(chan interface{})
multiPlex := func(c <-chan interface{}) {
defer wg.Done()
for i := range c {
select {
case <-done:
return
case multiPlexedStream <- i:
}
}
}
wg.Add(len(channels))
for _, c := range channels {
go multiPlex(c)
}
go func() {
wg.Wait()
close(multiPlexedStream)
}()
return multiPlexedStream
}