/
ping_pong.go
39 lines (35 loc) · 723 Bytes
/
ping_pong.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
package ping_pong
import "fmt"
func PingGen(msg string) <-chan string {
ch := make(chan string)
go func() {
for i := 0; ; i++ {
ch <- fmt.Sprintf("%s %d", msg, i)
}
}()
return ch
}
func PingGenWithQuit(msg string, quit chan bool) <-chan string {
ch := make(chan string)
go func() {
for i := 0; ; i++ {
select {
case ch <- fmt.Sprintf("%s %d", msg, i):
case <-quit:
fmt.Printf("stopped sending %s \n", msg)
return
}
}
}()
return ch
}
// chan<-, send chan
func Ping(chping chan<- string) {
chping <- "send ping"
close(chping)
}
//<-chan, receive chan
func Pong(chping <-chan string, chpong chan<- string) {
chpong <- "receive: " + <-chping + ", then send pong!"
close(chpong)
}