package main import ( "fmt" "sync" ) func main() { // Create a WaitGroup var wg sync.WaitGroup // Start three goroutines for i := 0; i < 3; i++ { wg.Add(1) // Add 1 to the WaitGroup go worker(&wg) // Start the worker goroutine } // Wait for all goroutines to complete wg.Wait() fmt.Println("All workers have finished") } // worker simulates some work by sleeping for one second func worker(wg *sync.WaitGroup) { defer wg.Done() // Decrement the WaitGroup counter when done fmt.Println("Worker started") // Simulate some work by sleeping time.Sleep(time.Second) fmt.Println("Worker finished") }
package main import ( "fmt" "net/http" "sync" ) func main() { // Create a WaitGroup var wg sync.WaitGroup // URLs to fetch urls := []string{"https://www.google.com", "https://www.github.com", "https://www.twitter.com"} // Fetch each URL asynchronously for _, url := range urls { wg.Add(1) // Add 1 to the WaitGroup go fetchURL(&wg, url) // Start the fetchURL goroutine } // Wait for all goroutines to complete wg.Wait() fmt.Println("All URLs have been fetched") } // fetchURL fetches a URL and prints the response status code func fetchURL(wg *sync.WaitGroup, url string) { defer wg.Done() // Decrement the WaitGroup counter when done fmt.Println("Fetching", url) resp, err := http.Get(url) if err != nil { fmt.Println("Error:", err) return } defer resp.Body.Close() fmt.Println(url, "returned", resp.Status) }In this example, we fetch three URLs using http.Get asynchronously. Each fetchURL goroutine obtains a URL, prints a message, and calls Done() to signal its completion. The main goroutine waits for all URLs to be fetched before printing a message. In summary, the example code uses Go sync WaitGroup Add to initialize the WaitGroup with the number of goroutines to wait for. Then, each worker goroutine decrements the counter by calling WaitGroup.Done() when it completes. Finally, the main goroutine blocks on WaitGroup.Wait() until all goroutines have completed. The sync package provides synchronization primitives like WaitGroup to coordinate the execution of multiple goroutines.