-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy path1-6-restoring-sequencing.go
51 lines (42 loc) · 1.18 KB
/
1-6-restoring-sequencing.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
// Kevin Chen (2017)
// Patterns from Pike's Google I/O talk, "Go Concurrency Patterns"
// Golang restoring sequencing after multiplexing
package main
import (
"fmt"
"time"
)
type Message struct {
str string
block chan int
}
func main() {
ch := fanIn(generator("Hello"), generator("Bye"))
for i := 0; i < 10; i++ {
msg1 := <-ch
fmt.Println(msg1.str)
msg2 := <-ch
fmt.Println(msg2.str)
<- msg1.block // reset channel, stop blocking
<- msg2.block
}
}
// fanIn is itself a generator
func fanIn(ch1, ch2 <-chan Message) <-chan Message { // receives two read-only channels
new_ch := make(chan Message)
go func() { for { new_ch <- <-ch1 } }() // launch two goroutine while loops to continuously pipe to new channel
go func() { for { new_ch <- <-ch2 } }()
return new_ch
}
func generator(msg string) <-chan Message { // returns receive-only channel
ch := make(chan Message)
blockingStep := make(chan int) // channel within channel to control exec, set false default
go func() { // anonymous goroutine
for i := 0; ; i++ {
ch <- Message{fmt.Sprintf("%s %d", msg, i), blockingStep}
time.Sleep(time.Second)
blockingStep <- 1 // block by waiting for input
}
}()
return ch
}