-
Notifications
You must be signed in to change notification settings - Fork 0
/
select_interface.go
60 lines (48 loc) · 1.17 KB
/
select_interface.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
package main
import (
"fmt"
"math/rand"
)
type Output struct {
Index int
Payload interface{}
}
func receive_1(inputs interface{}) (output <-chan *Output) {
doneChan := make(chan int)
inputChans := inputs.([]interface{})
outputChan := make(chan *Output)
defer close(doneChan)
go func(numChan int) {
for i := numChan; i > 0; i-- {
<-doneChan
}
close(outputChan)
}(len(outputChan))
for i, inputChan := range inputChans {
go func() { outputChan <- &Output{ Index: i, Payload: <-inputChan.(chan interface{})} }()
}
return outputChan
}
func main() {
inputs := make([]chan int, rand.Intn(10))
fmt.Println(len(inputs))
for i := 0; i < len(inputs); i++ {
inputs[i] = make(chan int)
go func() {
for j := 0; j < rand.Intn(1000); j++ {
inputs[i] <- j
}
}()
}
fmt.Println(len(inputs))
output := receive_1(inputs)
for {
select {
case rs, ok := <-output:
if !ok {
break
}
fmt.Printf("Received %v from %d", rs.Index, rs.Payload)
}
}
}