Home > Backend Development > Golang > Why does using `sync.WaitGroup` with external functions lead to a deadlock?

Why does using `sync.WaitGroup` with external functions lead to a deadlock?

Linda Hamilton
Release: 2024-11-06 00:50:02
Original
875 people have browsed it

Why does using `sync.WaitGroup` with external functions lead to a deadlock?

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

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

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!

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