Consider the following program demonstrating channels:
package main
import (
"fmt"
)
func pinger(c chan string) {
for i := 0; ; i++ {
c <- "ping"
}
}
func ponger(c chan string) {
for i := 0; ; i++ {
c <- "pong"
}
}
func printer(c chan string) {
for {
msg := <-c
fmt.Println(msg)
//time.Sleep(time.Second * 1)
}
}
func main() {
var c = make(chan string)
go pinger(c)
go ponger(c)
go printer(c)
var input string
fmt.Scanln(&input)
}
If I uncomment the time.Sleep
call, the output is "ping" and "pong" taking turns in a nice, predictable manner. However, adding the comment makes the order unpredictable. I'm a Go novice and wondering what enabled this synchronization. Why does adding a wait time make the rest of the channel feeder tow the line?