Like here I created a go playground sample: sGgxEh40ev, but cannot get it work.
quit := make(chan bool)
res := make(chan int)
go func() {
idx := 0
for {
select {
case <-quit:
fmt.Println("Detected quit signal!")
return
default:
fmt.Println("goroutine is doing stuff..")
res <- idx
idx++
}
}
}()
for r := range res {
if r == 6 {
quit <- true
}
fmt.Println("I received: ", r)
}
Output:
goroutine is doing stuff..
goroutine is doing stuff..
I received: 0
I received: 1
goroutine is doing stuff..
goroutine is doing stuff..
I received: 2
I received: 3
goroutine is doing stuff..
goroutine is doing stuff..
I received: 4
I received: 5
goroutine is doing stuff..
goroutine is doing stuff..
fatal error: all goroutines are asleep - deadlock!
Is this possible? Where am I wrong
The problem is that in the goroutine you use a
selectto check if it should abort, but you use thedefaultbranch to do the work otherwise.The
defaultbranch is executed if no communications (listed incasebranches) can proceed. So in each iterationquitchannel is checked, but if it cannot be received from (no need to quit yet),defaultbranch is executed, which unconditionally tries to send a value onres. Now if the main goroutine is not ready to receive from it, this will be a deadlock. And this is exactly what happens when the sent value is6, because then the main goroutine tries to send a value onquit, but if the worker goroutine is in thedefaultbranch trying to send onres, then both goroutines try to send a value, and none is trying to receive! Both channels are unbuffered, so this is a deadlock.In the worker goroutine you must send the value on
resusing a propercasebranch, and not in thedefaultbranch:And in the main goroutine you must break out from the
forloop so the main goroutine can end and so the program can end as well:Output this time (try it on the Go Playground):