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