Let's talk a little bit about
- https://golang.org/pkg/sync/#WaitGroup
A
With an example it will be crystal clear. Let's say we have a script that fetches URLs concurrently and we want to wait using
First we create a
s done getting the URL, defer will be run and
#golang #go #sync #WaitGroup #Done #Add #Wait
WaitGroup in sync library. First things first, the documentation is here:- https://golang.org/pkg/sync/#WaitGroup
A
WaitGroup waits for a collection of goroutines to finish. The main goroutine calls Add to set the number of goroutines to wait for. Then each of the goroutines runs and calls Done when finished. At the same time, Wait can be used to block until all goroutines have finished.With an example it will be crystal clear. Let's say we have a script that fetches URLs concurrently and we want to wait using
WaitGroup until all the fetches are complete:package main
import (
"sync"
)
type httpPkg struct{}
func (httpPkg) Get(url string) {}
var http httpPkg
func main() {
var wg sync.WaitGroup
var urls = []string{
"http://www.golang.org/",
"http://www.google.com/",
"http://www.somestupidname.com/",
}
for _, url := range urls {
// Increment the WaitGroup counter.
wg.Add(1)
// Launch a goroutine to fetch the URL.
go func(url string) {
// Decrement the counter when the goroutine completes.
defer wg.Done()
// Fetch the URL.
http.Get(url)
}(url)
}
// Wait for all HTTP fetches to complete.
wg.Wait()
}
First we create a
WaitGroup called wg and using range loop through the URLs on each iterration we use Add to increment WaitGroup counter/queue and run an anonymous function that gets a URL. When func is done getting the URL, defer will be run and
Done decrement the counter in WaitGroup. Finally we use Wait to actually wait for all http calls to get completed.NOTE: anonymous function is preceded with go keyword that runs the function concurrently.#golang #go #sync #WaitGroup #Done #Add #Wait
pkg.go.dev
sync package - sync - Go Packages
Package sync provides basic synchronization primitives such as mutual exclusion locks.