meto
meto

Reputation: 3719

Second channel causing deadlock even if independent

This is more a follow up question from this other post

I do not understand why adding a second channel (c2 in my case) will cause a deadlock. Channels are independent and I don't see why c2 is supposed to be blocked

Link to playground

func do_stuff(done chan bool) {
    fmt.Println("Doing stuff")
    done <- true
}

func main() {
    fmt.Println("Main")
    done := make(chan bool)
    go do_stuff(done)
    <-done
    //Up tp here everything works
    c2 := make(chan int)
    c2 <- 1
    fmt.Println("Exit ",<-c2)

}

Upvotes: 1

Views: 83

Answers (2)

Simon Fox
Simon Fox

Reputation: 6425

The statements

c2 := make(chan int)
c2 <- 1

will always block. Link to Playground.

Because the channel c2 is unbuffered, the send operation cannot proceed until another goroutine has received the value from the channel. There is no goroutine that can receive from the channel, therefore the send blocks forever.

The channels section in Effective Go is a good place to read about unbuffered channels. Also see the sections on channels and send in the Go Language Specification.

The program will work as I think you are expecting if you make c2 a buffered channel:

    c2 := make(chan int, 1)

With this change, the send can proceed without synchronizing with a receiver.

Link to Playground

Upvotes: 2

peterSO
peterSO

Reputation: 166578

The Go Programming Language Specification

Send statements

Communication blocks until the send can proceed. A send on an unbuffered channel can proceed if a receiver is ready.

No receiver is ready.

package main

func main() {
    c2 := make(chan int)
    c2 <- 1
}

Output:

fatal error: all goroutines are asleep - deadlock!

Upvotes: 4

Related Questions