30 lines
439 B
Go
30 lines
439 B
Go
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")
|
|
}
|