Wait Groups
This Go code demonstrates the use of the sync.WaitGroup
to wait for a collection of goroutines to finish their execution. Let's go through it with inline comments:
Output
Explanation:
package main
: Indicates that this Go file belongs to the main executable package.import (...)
: Imports necessary packages, including "fmt" for formatting and printing, "sync" for synchronization, and "time" for handling time-related operations.func worker(id int) { ... }
: Defines a worker function that simulates work by sleeping for one second and prints messages.var wg sync.WaitGroup
: Creates async.WaitGroup
variable named 'wg' to wait for a collection of goroutines to finish.wg.Add(1)
: Increments the WaitGroup counter for each goroutine to indicate that a new goroutine is starting.i := i
: Creates a local variable 'i' to capture the current value of the loop variable, preventing its value from changing in the closure.go func() { ... }()
: Launches a goroutine for each worker. Thedefer wg.Done()
statement is used to decrement the WaitGroup counter when the goroutine completes.wg.Wait()
: Waits for all goroutines to finish by blocking until the WaitGroup counter becomes zero.
This code demonstrates how to use a sync.WaitGroup
to coordinate the execution of multiple goroutines. Each worker is launched as a goroutine, and the WaitGroup is used to wait for all workers to complete their work before proceeding further in the main function. The use of a local variable inside the loop ensures that each goroutine captures the correct value of 'i'.
Last updated
Was this helpful?