1
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?

Ganeshdip
  • 389
  • 2
  • 10

1 Answers1

2

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?

icza
  • 389,944
  • 63
  • 907
  • 827
  • is the main routine marked as sleepy somewhere in the internal ? thus prevents the deadlock to trigger before the program exits ? the time.Sleep doc does not mention it. –  May 07 '20 at 10:36
  • 1
    @mh-cbon I haven't looked into the internals, but a sleep operation cannot take forever (the duration is finite), hence the deadlock detector shouldn't even bother with it. – icza May 07 '20 at 10:40
  • @icza so to conclude, if all the go routines are blocked at particular point, then it is a deadlock. – Ganeshdip May 07 '20 at 12:06
  • 1
    @Ganeshdip Yes. Blocked means the runtime can prove none of the goroutines will ever get out of the blocking state, so there is no point waiting forever for nothing. – icza May 07 '20 at 12:14
  • Just to clarify, the program does contain a deadlock under the generally accepted definition of deadlock (i.e. some part of the program is blocked waiting for something that will never occur). However, go's deadlock detector can only detect if the the entire program is in deadlock. The main thread is not deadlocked and so go's deadlock detector does not report anything. – Increasingly Idiotic May 07 '20 at 18:04