Wait Groups
package main
import (
"fmt"
"sync"
"time"
)
// worker function represents a worker that performs some work
func worker(id int) {
fmt.Printf("Worker %d starting\n", id)
// Simulate work by sleeping for one second
time.Sleep(time.Second)
fmt.Printf("Worker %d done\n", id)
}
func main() {
// Creating a WaitGroup to wait for all goroutines to finish
var wg sync.WaitGroup
for i := 1; i <= 5; i++ {
// Incrementing the WaitGroup counter for each goroutine
wg.Add(1)
// Creating a local variable 'i' to capture the current value
i := i
// Launching a goroutine for each worker
go func() {
// Decrementing the WaitGroup counter when the goroutine completes
defer wg.Done()
worker(i)
}()
}
// Waiting for all goroutines to finish
wg.Wait()
}Output
Last updated