Golang sync.WaitGroup Never Completes
The provided code demonstrates concurrency by fetching a list of URLs and conditionally downloading and saving files to the file system. The main goroutine waits for all files to be fetched using a sync.WaitGroup. However, the program fails to exit even after completing all requests.
To understand the issue, consider the WaitGroup's functionality. It maintains a count of the executing goroutines. If the count ever reaches zero, the waitgroup returns immediately, indicating all goroutines have completed execution.
In the given code, the WaitGroup's Add method is used to increment the count, while the Done method is used to decrement it. If the Add method is called more times than the Done method, or vice versa, the WaitGroup will never reach zero, causing the main goroutine to wait indefinitely.
There are two errors in the provided code:
func main() { ... go downloadFromURL(url, &wg) ... }
func downloadFromURL(url string, wg *sync.WaitGroup) error { defer wg.Done() ... }
With these corrections in place, the WaitGroup will function correctly, decrementing its count as goroutines complete their tasks, ultimately leading to the main goroutine's successful exit.
The above is the detailed content of Why Doesn\'t My Go sync.WaitGroup Ever Complete?. For more information, please follow other related articles on the PHP Chinese website!