gobyexample/waitgroups/waitgroups.go

30 lines
439 B
Go
Raw Normal View History

2024-04-29 02:17:21 +00:00
package waitgroups
import (
"fmt"
"math/rand"
"sync"
"time"
)
func worker(id int, wg *sync.WaitGroup) {
defer wg.Done()
fmt.Printf("worker #%d starting\n", id)
time.Sleep(time.Duration((1 + rand.Intn(2))) * time.Second)
fmt.Printf("worker #%d exiting\n", id)
}
func WaitGroups() {
numJobs := 3
wg := sync.WaitGroup{}
for i := range numJobs {
wg.Add(1)
go worker(i, &wg)
}
wg.Wait()
fmt.Println("Program exiting")
}