-
Notifications
You must be signed in to change notification settings - Fork 0
/
pre-select.go
77 lines (69 loc) · 1.18 KB
/
pre-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"
"sync"
"time"
)
type Output struct {
Index int
Payload int
}
func receive(inputs []chan int) <-chan *Output {
//START OMIT
var wg sync.WaitGroup
output := make(chan *Output)
for i, input := range inputs {
wg.Add(1)
go func(index int, input chan int) {
L:
for {
select {
case payload, ok := <-input:
if !ok {
wg.Done()
break L
}
output <- &Output{Index: index, Payload: payload}
}
}
}(i, input)
}
go func(numChan int) {
defer close(output)
wg.Wait()
}(len(inputs))
//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() {
rand.Seed(time.Now().Unix())
printOutput(receive(getChannels()))
}