I am working on the GoLang Tutorial Select.go
func fibonacci(c, quit chan int) {
x, y := 0, 1
for {
select {
case c <- x:
x, y = y, x+y
case <-quit:
fmt.Println("quit")
return
}
}
}
func main() {
c := make(chan int)
quit := make(chan int)
go func() {
for i := 0; i < 10; i++ {
fmt.Println(<-c)
}
quit <- 0
}()
fibonacci(c, quit)
}
For the 2nd case statement, I understand that it will be triggered when something comes through the quit channel. But I don't understand why the 1st case statement will be also triggered. It is just plainly pushing into pipe. It does not look like some "wait-and-trigger" scenario. More broadly, what are the criteria to judge if the case statement is triggered?
In this case it looks like some "wait-and-trigger" scenario. One can send in unbuffered channel only when receiver side of pipe can receive. Unbuffered channels are like rendezvous. So c <- x
can't proceed before fmt.Println(<-c)
done with print and ready for receiving new value. In case of many possible choices case is chosen via a uniform pseudo-random selection. So the criteria to judge is just a probability. If many goroutings want to send or receive from a channel, then perhaps it would be triggered rather then rare case.