Home > Backend Development > Golang > Why does using a copy of Sync.WaitGroup in an external function lead to missing output in a goroutine?

Why does using a copy of Sync.WaitGroup in an external function lead to missing output in a goroutine?

Mary-Kate Olsen
Release: 2024-11-06 14:00:03
Original
568 people have browsed it

Why does using a copy of Sync.WaitGroup in an external function lead to missing output in a goroutine?

Using Sync.WaitGroup with External Functions

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>
Copy after login

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>
Copy after login

In this case, the main goroutine must wait on the channel's closure instead:

<code class="go">wg.Wait()
close(ch)</code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template