Welcome to your comprehensive guide on the sync.WaitGroup in Golang! This lesson is designed to help you understand and master concurrency, making your Go applications more efficient and powerful. Let's dive in!
Concurrency is the ability of a system to execute multiple tasks simultaneously. In Go, we can achieve concurrency using Goroutines and sync.WaitGroup.
sync.WaitGroup is a Go package that helps manage multiple Goroutines. It allows you to wait for multiple Goroutines to finish executing before moving forward with the main routine.
To create a WaitGroup, use the sync.NewWaitGroup function.
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
// ...
}Use the Add method to specify the number of Goroutines that will be executed. Call the Done method in each Goroutine once it finishes executing.
wg.Add(10) // Add 10 Goroutines to be executed
go func() {
defer wg.Done() // Call Done when Goroutine finishes
// ...
}()Call the Wait method on the WaitGroup instance to block the main Goroutine until all the added Goroutines have completed execution.
wg.Wait()In this example, we'll download the contents of multiple URLs concurrently using Goroutines and sync.WaitGroup.
package main
import (
"fmt"
"io"
"net/http"
"os"
"sync"
)
func main() {
urls := []string{
"https://example.com/file1.txt",
"https://example.com/file2.txt",
// Add more URLs here
}
var wg sync.WaitGroup
for _, url := range urls {
wg.Add(1)
go func(url string) {
defer wg.Done()
resp, err := http.Get(url)
if err != nil {
fmt.Printf("Error downloading %s: %v\n", url, err)
return
}
defer resp.Body.Close()
file, err := os.CreateTemp("", "download")
if err != nil {
fmt.Printf("Error creating temp file: %v\n", err)
return
}
defer file.Close()
_, err = io.Copy(file, resp.Body)
if err != nil {
fmt.Printf("Error saving file for %s: %v\n", url, err)
} else {
fmt.Printf("Successfully downloaded %s\n", url)
}
}(url)
}
wg.Wait()
fmt.Println("All downloads complete.")
}What is the primary purpose of the `sync.WaitGroup` in Go?
Happy coding! Let's conquer the world of concurrency with Go sync.WaitGroup! 🎉