-
Notifications
You must be signed in to change notification settings - Fork 44
/
fan_in.go
53 lines (50 loc) · 991 Bytes
/
fan_in.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
package concurrent
import "reflect"
// FanInRec 扇入模式
func FanInRec(channels ...<-chan interface{}) <-chan interface{} {
out := make(chan interface{}, 1)
go func() {
defer close(out)
var cases []reflect.SelectCase
for _, channel := range channels {
cases = append(cases, reflect.SelectCase{
Dir: reflect.SelectRecv,
Chan: reflect.ValueOf(channel),
})
}
for len(cases) > 0 {
i, v, ok := reflect.Select(cases)
if !ok {
// 监控的channel已经关闭
cases = append(cases[:i], cases[i+1:]...)
continue
}
out <- v.Interface()
}
}()
return out
}
// MergeChannel 合并两个channel
func MergeChannel(a, b <-chan interface{}) <-chan interface{} {
c := make(chan interface{})
go func() {
defer close(c)
for a != nil || b != nil {
select {
case v, ok := <-a:
if !ok {
a = nil
continue
}
c <- v
case v, ok := <-b:
if !ok {
b = nil
continue
}
c <- v
}
}
}()
return c
}