"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Avoid Deadlock When Ranging Over a Buffered Channel in GoLang?

How to Avoid Deadlock When Ranging Over a Buffered Channel in GoLang?

Published on 2024-11-02
Browse:600

How to Avoid Deadlock When Ranging Over a Buffered Channel in GoLang?

Deadlock in GoLang: Why Range Over a Buffered Channel?

When using buffered channels in GoLang, it's important to avoid creating a deadlock situation. A recent issue raised concerns about a deadlock encountered while attempting to range over a buffered channel after all goroutines had completed.

The provided code attempts to use a buffered channel with a capacity of 4 and spawn 4 goroutines that send data to the channel. However, the deadlock occurs because:

  • The channel size is too small, resulting in blocked goroutines waiting to write to the full channel.
  • The range over operation on the channel remains indefinitely waiting for elements to arrive, while no goroutines are left to write.

Solution 1: Expand Channel Size and Close After Completion

To resolve the deadlock, the channel can be increased in size and closed after all goroutines have completed:

ch := make(chan []int, 5)
...
wg.Wait()
close(ch)

However, this eliminates the benefits of pipelining, as it prevents printing until all tasks are finished.

Solution 2: Signal Completion from within Printing Routine

To enable actual pipelining, the Done() function can be called within the printing routine:

func main() {
    ch := make(chan []int, 4)
    ...
    go func() {
        for c := range ch {
            fmt.Printf("c is %v\n", c)
            wg.Done()
        }
    }()
    ...
}

This approach ensures that the Done() function is only called after each element has been printed, effectively signaling the completion of each goroutine.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3