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
select
to check if it should abort, but you use thedefault
branch to do the work otherwise.The
default
branch is executed if no communications (listed incase
branches) can proceed. So in each iterationquit
channel is checked, but if it cannot be received from (no need to quit yet),default
branch 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 thedefault
branch 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
res
using a propercase
branch, and not in thedefault
branch:And in the main goroutine you must break out from the
for
loop so the main goroutine can end and so the program can end as well:Output this time (try it on the Go Playground):