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() {
    done := make(chan bool)
    go do_stuff(done)
    //Up tp here everything works
    c2 := make(chan int)
    c2 <- 1
    fmt.Println("Exit ",<-c2)



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

Answered By – Simon Fox

Answer Checked By – Cary Denson (GoLangFix Admin)

Leave a Reply

Your email address will not be published.