Home > Back-end >  Gorountines causing a deadlock
Gorountines causing a deadlock

Time:02-13

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?

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

CodePudding user response:

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

  • Related