/
post-select.go
77 lines (66 loc) · 1.26 KB
/
post-select.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
package main
import (
"fmt"
"math/rand"
"reflect"
"time"
)
type Output struct {
Index int
Payload int
}
func receive(inputs []chan int) <-chan *Output {
//START OMIT
cases := make([]reflect.SelectCase, len(inputs))
output := make(chan *Output)
for i, input := range inputs {
cases[i] = reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(input)}
}
go func() {
defer close(output)
for {
index, recv, ok := reflect.Select(cases)
if !ok {
cases[index] = cases[len(cases)-1]
cases = cases[0 : len(cases)-1]
if len(cases) == 0 {
break
}
continue
}
output <- &Output{Index: index, Payload: int(recv.Int())}
}
}()
//END OMIT
return output
}
func getChannels() []chan int {
inputs := make([]chan int, 10)
for i := 0; i < len(inputs); i++ {
input := make(chan int)
go func() {
defer close(input)
for j := 0; j < 10; j++ {
input <- j
time.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond)
}
}()
inputs[i] = input
}
return inputs
}
func printOutput(output <-chan *Output) {
L:
for {
select {
case rs, ok := <-output:
if !ok {
break L
}
fmt.Printf("Received from %d: %d\n", rs.Index, rs.Payload)
}
}
}
func main() {
printOutput(receive(getChannels()))
}