Search code examples
gogoroutine

Why does chan not deadlock in goroution?


package main
func main() {
    ch1 := make(chan int)
    go pump(ch1) // pump hangs
}
func pump(ch chan int) {
    ch <- 1
    ch <- 2
}

Why is it that there is nothing wrong with writing a corruption? Blocking the main process will deadlock


Solution

  • Because the main() function exits and terminates the program while the pump() goroutine is blocked writing to the channel.

    I think this code does what you expect:

    package main
    func main() {
        ch1 := make(chan int)
        done := make(chan struct{})
        go pump(ch1, done) // pump hangs
        <-done // wait for pump
    }
    func pump(ch chan int, done chan struct{}) {
        ch <- 1
        ch <- 2 // never reached
        close(done) // never reached
    }
    

    Output:

    fatal error: all goroutines are asleep - deadlock!
    
    goroutine 1 [chan receive]:
    main.main()
        /tmp/sandbox778506014/main.go:7 +0xc0
    
    goroutine 4 [chan send]:
    main.pump(0x1043a080, 0x1043a0c0)
        /tmp/sandbox778506014/main.go:10 +0x40
    created by main.main
        /tmp/sandbox778506014/main.go:6 +0xa0
    

    Playground: https://play.golang.org/p/FTFPOBCm4G_0