I tried changing a little bit on the code when learning Go select statement in Golang tour: https://tour.golang.org/concurrency/5. However, i got issue:
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.main()
concurrency.go:26 +0xa3
goroutine 33 [chan receive]:
main.main.func1(0xc000088000)
concurrency.go:24 +0x42
created by main.main
concurrency.go:23 +0x89
exit status 2
Here is the code i tried and got the issue
func fibonacci(c, quit chan int) {
x, y := 0, 1
for {
select {
case c <- x: //sending value x into channel c
x, y = y, x+y
case <-quit: //receive value from quit
fmt.Println("quit")
return
}
}
}
func main() {
//create two channels
c := make(chan int)
quit := make(chan int)
go func() { //spin off the second function in order to let consume from c , so fibonaci can continue to work
fmt.Println(<-c) //read value from channel c
}()
//Try moving the statement that send value to channel quit in order to
//return function fibonacci
quit <- 0
fibonacci(c, quit)
}
At first, i thought that the result will be same with result of below code
//function fibonacci is same with the first one
func fibonacci(c, quit chan int) {
x, y := 0, 1
for {
select {
case c <- x: //sending value x into channel c
x, y = y, x+y
case <-quit: //receive value from quit
fmt.Println("quit")
return
}
}
}
func main() {
//create two channels
c := make(chan int)
quit := make(chan int)
go func() { //spin off the second function in order to let consume from c , so fibonaci can continue to work
fmt.Println(<-c) //read value from channel c
quit <- 0 //CHANGE: move the statement inside the closure function
}()
fibonacci(c, quit)
}
The output is
0
quit
Can you please explain what's the root cause of deadlock when executing the first example? And what are differences when sending value to quit channel in the go routines with sending value to quit channel in the main thread.
Thank you guys.