Best Practice for Utilizing sync.WaitGroup with External Functions
In the code snippet provided, you encounter a deadlock when attempting to utilize a sync.WaitGroup with an external function. The error stems from incorrectly passing a copy of the WaitGroup to the external function, resulting in the Done() method not being invoked on the intended WaitGroup.
To address this issue, ensure that you pass a pointer to the WaitGroup instead. By doing so, the external function can access the correct WaitGroup and call Done() appropriately. Here's the corrected code:
<code class="go">package main import ( "fmt" "sync" ) func main() { ch := make(chan int) var wg sync.WaitGroup wg.Add(2) go Print(ch, &wg) // Pass a pointer to the WaitGroup go func() { for i := 1; i <= 11; i++ { ch <- i } close(ch) defer wg.Done() }() wg.Wait() // Wait for both goroutines to finish } func Print(ch <-chan int, wg *sync.WaitGroup) { for n := range ch { // Read from the channel until it's closed fmt.Println(n) } defer wg.Done() }</code>
Alternatively, you could modify the signature of the Print function to remove the WaitGroup parameter, as shown below:
<code class="go">func Print(ch <-chan int) { for n := range ch { // Read from the channel until it's closed fmt.Println(n) } }</code>
In this case, the Print function is responsible for closing the WaitGroup when it's done. This approach is preferable in scenarios where the external function does not require direct access to the WaitGroup.
The above is the detailed content of Why does using `sync.WaitGroup` with external functions lead to a deadlock?. For more information, please follow other related articles on the PHP Chinese website!