Home >Backend Development >Golang >Why am I getting - goroutines are sleeped error because of producer consumer issue

Why am I getting - goroutines are sleeped error because of producer consumer issue

WBOY
WBOYforward
2024-02-10 21:40:251021browse

为什么我会收到 - goroutines are sleeped 错误,因为生产者消费者问题

php editor Youzi may encounter a common error message when solving programming problems: "goroutines are sleeped". This error is usually related to producer-consumer issues. The producer-consumer problem is a classic scenario in concurrent programming, where one or more producers generate data and one or more consumers take it out for processing. When the producer generates data faster than the consumer can process the data, it may cause goroutines (lightweight threads in the Go language) to go to sleep. This article will explain why this error occurs and provide a solution.

Question content

This is the code - producer and multiple consumers in go routine. The producer is injecting information into a channel, and multiple consumers (each via a go-routine) should read 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()
}

This is the link to the playground - https://go.dev/play/p/yndataeexpb

The error I received is this -

one Second c Fatal error: all goroutines are sleeping - deadlock!

Solution

Close the channel after the producer is finished so that the consumer knows when to stop:

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

Let the waiting group know when the consumer is finished:

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

The above is the detailed content of Why am I getting - goroutines are sleeped error because of producer consumer issue. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete