-
Notifications
You must be signed in to change notification settings - Fork 0
/
chan_ordone_test.go
88 lines (77 loc) · 1.32 KB
/
chan_ordone_test.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
package main
import (
"fmt"
"reflect"
"testing"
"time"
)
func TestOrDone(t *testing.T) {
startTime := time.Now()
<-Or(
Sig(4*time.Second),
Sig(5*time.Second),
Sig(6*time.Second),
)
fmt.Println("done after", time.Since(startTime))
<-OrWithReflect(
Sig(4*time.Second),
Sig(5*time.Second),
Sig(6*time.Second),
)
fmt.Println("done after", time.Since(startTime))
}
func Sig(d time.Duration) <-chan interface{} {
c := make(chan interface{})
go func() {
defer close(c)
time.Sleep(d)
}()
return c
}
func OrWithReflect(cs ...<-chan interface{}) <-chan interface{} {
switch len(cs) {
case 0:
return nil
case 1:
return cs[0]
}
orDone := make(chan interface{})
go func() {
defer close(orDone)
var cases []reflect.SelectCase
for _, c := range cs {
cases = append(cases, reflect.SelectCase{
Dir: reflect.SelectRecv,
Chan: reflect.ValueOf(c),
})
}
reflect.Select(cases)
}()
return orDone
}
func Or(cs ...<-chan interface{}) <-chan interface{} {
switch len(cs) {
case 0:
return nil
case 1:
return cs[0]
}
orDone := make(chan interface{})
go func() {
defer close(orDone)
switch len(cs) {
case 2:
select {
case <-cs[0]:
case <-cs[1]:
}
default:
m := len(cs) / 2
select {
case <-Or(cs[:m]...):
case <-Or(cs[m:]...):
}
}
}()
return orDone
}