-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path06_muxwithsequence.go
59 lines (54 loc) · 905 Bytes
/
06_muxwithsequence.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
package main
import (
"fmt"
"math/rand"
"runtime"
"time"
)
var a = [5]int{1, 2, 3, 4, 5}
func generate(marker string, wait chan bool) chan string {
c := make(chan string)
go func() {
count := 0
for {
c <- fmt.Sprintf("%s %d", marker, count)
count++
time.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond)
if marker == "aa" {
time.Sleep(1 * time.Second)
}
<-wait
}
close(c)
}()
return c
}
func fanIn(c1, c2 chan string) chan string {
mux := make(chan string)
go func() {
for {
mux <- <-c1
}
}()
go func() {
for {
mux <- <-c2
}
}()
return mux
}
func main() {
runtime.GOMAXPROCS(10)
wait1 := make(chan bool)
wait2 := make(chan bool)
c1 := generate("aa", wait1)
c2 := generate("bb", wait2)
mux := fanIn(c1, c2)
defer close(mux)
for i := 0; i < 5; i++ {
fmt.Println(<-mux)
fmt.Println(<-mux)
wait1 <- true
wait2 <- true
}
}