Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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))

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading