How it works...
This recipe shows how to use waitgroups as a synchronization mechanism when waiting for work. In essence, waitgroup.Wait() will wait until its internal counter has reached 0. The waitgroup.Add(int) method will increment the counter by the amount entered, and waitgroup.Done() will decrement the counter by 1. Because of this, it is necessary to asynchronously Wait() while the various goroutines mark the waitgroup as Done().
In this recipe, we increment before dispatching each HTTP request and then call a defer wg.Done() method, so that we can decrement whenever the goroutine terminates. We then wait for all goroutines to finish before returning our aggregated results.
In practice, it's better to use channels for passing the ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access