Ganeshdip
Ganeshdip

Reputation: 389

Go channel deadlock is not happening

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?

Upvotes: 1

Views: 104

Answers (1)

icza
icza

Reputation: 417642

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?

Upvotes: 2

Related Questions