Optimal Use of sync.WaitGroup with External Functions
Issue:
Implementing sync.WaitGroup with an external function is causing a deadlock when attempting to print numbers 1 to 11. Specifically, the error occurs at the wg.Wait() line.
Solution 1 (Incorrect Approach):
Setting wg.Add(1) instead of 2 is an incorrect solution, as it does not address the fundamental issue.
Solution 2 (Improved Approach):
Modify the code as follows:
<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) go func() { for i := 1; i <= 11; i++ { ch <- i } close(ch) wg.Done() }() wg.Wait() //deadlock here } func Print(ch <-chan int, wg *sync.WaitGroup) { for n := range ch { // reads from channel until it's closed fmt.Println(n) } wg.Done() }</code>
Explanation:
Passing the address of wg to Print ensures that the same WaitGroup instance is being manipulated. Removing wg from the Print function signature eliminates the need for the function to know about the external WaitGroup.
Conclusion:
The second solution is a more robust approach that avoids deadlocks and maintains the independence of the Print function from wg.
The above is the detailed content of How to Avoid Deadlock When Using sync.WaitGroup with an External Function?. For more information, please follow other related articles on the PHP Chinese website!