Home >Backend Development >Golang >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:
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:
<code class="go">ch := make(chan []int, 5) ... wg.Wait() close(ch)</code>
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:
<code class="go">func main() { ch := make(chan []int, 4) ... go func() { for c := range ch { fmt.Printf("c is %v\n", c) wg.Done() } }() ... }</code>
This approach ensures that the Done() function is only called after each element has been printed, effectively signaling the completion of each goroutine.
The above is the detailed content of How to Avoid Deadlock When Ranging Over a Buffered Channel in GoLang?. For more information, please follow other related articles on the PHP Chinese website!