Home > Backend Development > Golang > How to Avoid Deadlock When Using sync.WaitGroup with an External Function?

How to Avoid Deadlock When Using sync.WaitGroup with an External Function?

Mary-Kate Olsen
Release: 2024-11-06 05:06:02
Original
669 people have browsed it

How to Avoid Deadlock When Using sync.WaitGroup with an External Function?

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:

  • In the main function, pass the address of the sync.WaitGroup to the Print function using &wg.
  • Remove the wg parameter from the Print function signature.
<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>
Copy after login

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!

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