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:
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.
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