Goroutines and WaitGroup in Go
Starting concurrent work and waiting for it.
func fanOut(jobs []string) {
var wg sync.WaitGroup
for _, job := range jobs {
wg.Add(1)
go func(name string) {
defer wg.Done()
fmt.Println("working on", name)
}(job)
}
wg.Wait()
}
How it works
go func()launches a goroutine.wg.Add/wg.Donetrack outstanding work.wg.Waitblocks until every goroutine finishes.
Keywords and builtins used here
deferforfuncgorangestringvar
The run, in numbers
- Lines
- 11
- Characters to type
- 179
- Tokens
- 60
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 38 seconds.
Step 1 of 3 in Goroutines, step 1 of 25 in Concurrency.