Home > Mobile >  Why do I get - go routines are asleep error for producer consumer issue
Why do I get - go routines are asleep error for producer consumer issue

Time:12-21

Here is the code - a producer in go routine and multiple consumers. The producer is pumping a channel with information and multiple consumers ( each via a go-routine ) should be reading it in parallel.

func main() {
    alphabetArray := []string{"A", "B", "C"}

    alphabetChannel := make(chan string, 3)
    // producer.
    go func() {
        for _, alphabet := range alphabetArray {
            alphabetChannel <- alphabet
        }
    }()

    var wg sync.WaitGroup
    // spawn 10 consumers, consumers represented as a go-routine.
    for idx := 0; idx < 10; idx   {
        wg.Add(1)
        go func() {
            for alphabet := range alphabetChannel {
                fmt.Println(alphabet)
            }
        }()
    }
    wg.Wait()
}

Here is the link to go playground - https://go.dev/play/p/yNdATAEexPB

The error I am getting is this -

A B C fatal error: all goroutines are asleep - deadlock!

CodePudding user response:

Close the channel after producer is done, so the consumer would know when to stop:

go func() {
        defer close(alphabetChannel)
        for _, alphabet := range alphabetArray {
            alphabetChannel <- alphabet
        }
    }()

Let the waitgroup know when consumers are done:

go func() {
            defer wg.Done()
            for alphabet := range alphabetChannel {
                fmt.Println(alphabet)
            }
        }()
  • Related