Home > Article > Backend Development > Why does using a copy of Sync.WaitGroup in an external function lead to missing output in a goroutine?
In the code provided, the intention is for the primary goroutine to print numbers from 1 to 11 by utilizing a channel and a wait group. However, it occasionally skips number 11, resulting in an incomplete output.
The issue arises from the incorrect传递 of sync.WaitGroup to the external function, Print. By passing a copy of WaitGroup to the function, it can't perform the necessary Done() call on the original wait group being waited on by the main goroutine.
Best Solution:
The recommended solution involves modifying the code as follows:
<code class="go">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) defer wg.Done() }() wg.Wait() } func Print(ch <-chan int, wg *sync.WaitGroup) { for n := range ch { // reads from channel until it's closed fmt.Println(n) } defer wg.Done() }</code>
In this fix, the Print function receives a pointer to the wait group, ensuring that its Done() method is called within the function, thus allowing the main goroutine to proceed correctly.
Alternative Solution:
Alternatively, one can eliminate the need for WaitGroup within the Print function by directly closing the channel after sending all numbers:
<code class="go">func Print(ch <-chan int) { for n := range ch { // reads from channel until it's closed fmt.Println(n) } }</code>
In this case, the main goroutine must wait on the channel's closure instead:
<code class="go">wg.Wait() close(ch)</code>
The above is the detailed content of Why does using a copy of Sync.WaitGroup in an external function lead to missing output in a goroutine?. For more information, please follow other related articles on the PHP Chinese website!