User Tools

Site Tools


pingpong2.go
package main
 
import (
    "fmt"
    "time"
)
 
func pinger0(c chan string) {
    for i := 0; ; i++ {
        c <- "ping0"
    }
}
 
 
func pinger1(c chan string) {
    for i := 0; ; i++ {
        c <- "ping1"
    }
}
 
func printer(c0 chan string, c1 chan string) {
 
    for {
        select {
 
        case msg0 := <- c0:
            fmt.Println("Message 0", msg0)
 
        case msg1 := <- c1:
            fmt.Println("Message 1", msg1)
 
        case <- time.After(time.Second):
            fmt.Println("timeout")
 
        default:
            fmt.Println("nothing ready")
        }
 
        time.Sleep(time.Microsecond * 100)
    }
}
 
 
func main() {
    var c0 chan string = make(chan string, 5)
    var c1 chan string = make(chan string, 5)
 
    go pinger0(c0)
    go pinger1(c1)
    go printer(c0, c1)
 
    for {}
 
}
# go run ping-pong.go 
Message 1 ping1
Message 0 ping0
Message 1 ping1
Message 0 ping0
Message 0 ping0
Message 0 ping0
Message 1 ping1
Message 0 ping0
Message 0 ping0
Message 1 ping1
Message 1 ping1
Message 1 ping1
Message 1 ping1
Message 0 ping0
Message 1 ping1
Message 0 ping0
Message 0 ping0
Message 1 ping1
Message 1 ping1
Message 0 ping0
Message 0 ping0
Message 1 ping1
^Csignal: interrupt