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

Gorountines causing a deadlock

I am trying my hands on goroutines and came up this example – https://go.dev/play/p/mWHUmALk-1_K

But I am having this error – fatal error: all goroutines are asleep - deadlock!

I have tried to fix this but no luck. Please how do I fix this?

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

The error seem to be on lines 15, 23 and 32.

>Solution :

The problem is that your program starts 3 separate goroutines that send to the same channel. And you have only the main goroutine receive from that channel only once. This causes the second channel send (ch <- fmt.Sprintf("...) to block indefinitely. With unbuffered channels you need to do as many receives as you do sends.

One approach to ensure all sends are received would be to use a range loop over the channel.

func getLength(dd []string, wg *sync.WaitGroup) {
    wg.Add(len(dd))
    c := make(chan string)
    for _, d := range dd {
        d1 := d
        go computeLength(d1, c, wg)
    }

    // close c once all goroutines are done to
    // ensure the for-range loop below exits.
    go func() { wg.Wait(); close(c) }()

    // Use for-range loop on the channel to receive all the sends.
    //
    // But note that a for-range loop over a channel exits only
    // when the channel is closed or the loop is exited from within.
    //
    // So to exit you can close c once wg.Wait() returns,
    // that's why there's that extra goroutine above.
    for v := range c {
        fmt.Println(v)
    }
}

https://go.dev/play/p/BUb7NHrq2B0

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