Deadlocks in Go with WaitGroup and Buffered Channels
In Go, a deadlock occurs when multiple goroutines are waiting for each other to complete, resulting in a stalemate. This situation can arise when using buffered channels and WaitGroups incorrectly.
Consider the following code:
<code class="go">package main import "fmt" import "sync" func main() { ch := make(chan []int, 4) var m []int var wg sync.WaitGroup for i := 0; i < 5; i++ { wg.Add(1) go func() { defer wg.Done() ch <- m return }() } wg.Wait() for c := range ch { fmt.Printf("c is %v", c) } }</code>
This code is expected to create a channel with a buffer size of 4 and start 5 goroutines, each sending an empty slice to the channel. The main goroutine waits for all goroutines to finish and then ranges over the channel.
However, this code will result in a deadlock. Why?
Cause of the Deadlock:
Two problems exist in the code:
Solutions:
Increase Channel Capacity: By increasing the channel capacity to 5, enough slots will be available for all goroutines to send their values without blocking. Additionally, closing the channel after the goroutines have finished writing will signal to the range loop that no more elements are coming, preventing it from waiting indefinitely.
<code class="go">ch := make(chan []int, 5) ... wg.Wait() close(ch)</code>
Use Done() within the Loop: Instead of closing the channel, one can use the Done() method of WaitGroup to signal when the last goroutine has finished. By calling Done() within the range loop, the main goroutine will be notified when the channel is empty and the loop can exit.
<code class="go">go func() { for c := range ch { fmt.Printf("c is %v\n", c) wg.Done() } }() wg.Wait()</code>
These solutions resolve the deadlock by ensuring that the channel has sufficient capacity and that the range loop exits when there are no more elements to read from the channel.
The above is the detailed content of Why does the provided Go code with WaitGroup and buffered channel result in a deadlock?. For more information, please follow other related articles on the PHP Chinese website!