fatal error: all goroutines are asleep – deadlock — simple loop

Advertisements

Consider the following example:

func main {

    channelBuffering()

}


func channelBuffering() {
    messages := make(chan string)
    messages <- "bufferedl"
    msg := <-messages
    fmt.Println(msg)
}

But the following works:

package main

    

import "fmt"

    

func main() {
    messages := make(chan string)
    go func() { messages <- "ping" }()
    msg := <-messages
    fmt.Println(msg)
}

Panics with "All goroutines are asleep – deadlock", I did take a look at the duplicate questions, but none answer this scenario.
Thanks for your help.

>Solution :

In the first example, deadlock happens because the channelBuffering function is trying to send and receive a message on an unbuffered channel in the same thread. The second example works because the sender is in a separate goroutine (the anonymous function started with go statement).

The thing to remember is that the messages chan is unbuffered. This means that the receiver and the sender will have to rendezvous to exchange a message (i.e. simultaneously). The first example could be made to work by creating a buffered channel (e.g. messages := make(chan string, 1))

Leave a ReplyCancel reply