Home >Backend Development >Golang >Why Doesn\'t My Go WaitGroup Complete When Downloading Files Concurrently?

Why Doesn\'t My Go WaitGroup Complete When Downloading Files Concurrently?

Barbara Streisand
Barbara StreisandOriginal
2024-11-28 07:35:12765browse

Why Doesn't My Go WaitGroup Complete When Downloading Files Concurrently?

WaitGroup Not Completing in Go Concurrency

The provided code attempts to concurrently download and save multiple files from a list of URLs. However, the main goroutine never terminates because the sync.WaitGroup never completes.

Two Issues Identified:

  1. Synchronization Issues:
    In downloadFromURL(), the wg.Done() call should be invoked as one of the first statements, not at the end of the function. This ensures that the WaitGroup decrements correctly even if the function returns early.
  2. Concurrency Pointer:
    The downloadFromURL() function should receive a pointer to the sync.WaitGroup to manipulate the shared object correctly. Otherwise, passing the WaitGroup by value creates a copy, and changes made to the copy will not be reflected in the main goroutine.

Optimized Code:

func downloadFromURL(url string, wg *sync.WaitGroup) error {
    defer wg.Done()  // Moved to the beginning of the function

    ... // Other code
}

func main() {
    ...

    for _, url := range links {
        if isExcelDocument(url) {
            wg.Add(1)
            go downloadFromURL(url, &wg)  // Pass pointer to WaitGroup
        } else {
            fmt.Printf("Skipping: %v \n", url)
        }
    }
    ...
}

By addressing these issues, the WaitGroup will accurately track the number of running goroutines, and the main goroutine will terminate once all downloads are complete.

The above is the detailed content of Why Doesn\'t My Go WaitGroup Complete When Downloading Files Concurrently?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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