Why do I not get a deadlock when trying to read from a channel that never receives data in a goroutine but do in the main func

Issue

Why do I get a deadlock here

c := make(chan bool)
fmt.Println(<-c)
fmt.Println("done")

and not here

c := make(chan bool)
go func() {
    fmt.Println(<-c)
}()
fmt.Println("done")

I was expecting a deadlock in both cases because both are trying to read from a channel that is never going to receive data.

Solution

The child goroutine is blocked, but the current goroutine can proceed with its execution.

You get a deadlock only when all goroutines are blocked at the same time.

Answered By – LeGEC

Answer Checked By – David Marino (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.