Go channel deadlock is not happening

Issue

package main
import (
    "fmt"
    "time"
)

func main() {
    c := make(chan int)

    go func() {
        fmt.Println("hello")
        c <- 10
    }()

    time.Sleep(2 * time.Second)
}

In the above program, I have created a Go routine which is writing to channel c but there is no other go routine which is reading from the channel. Why isnt there a deadlock in this case?

Solution

A deadlock implies all goroutines being blocked, not just one arbitrary goroutine of your choosing.

The main goroutine is simply in a sleep, once that is over, it can continue to run.

If you switch the sleep with a select{} blocking forever operation, you’ll get your deadlock:

c := make(chan int)

go func() {
    fmt.Println("hello")
    c <- 10
}()

select {}

Try it on the Go Playground.

See related: Why there is no error that receiver is blocked?

Answered By – icza

Answer Checked By – Marilyn (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.