WaitGroups are commonly used in order to validate the fact that multiple goroutines have completed. We do this in order to make sure we have completed all of the concurrent work that we expect to complete.
In the example in the following code block, we make requests to four websites with a WaitGroup. This WaitGroup will wait until all of our requests have been completed, and will only finish the main function after all of the WaitGroup values have been returned:
- First, we initialize our packages and set up our retrieval function:
package main
import (
"fmt"
"net/http"
"sync"
"time"
)
func retrieve(url string, wg *sync.WaitGroup) {
// WaitGroup Counter-- when goroutine is finished
defer wg.Done()
start := time.Now()
res, err := http.Get(url)
end := time.Since(start)
...