-
Notifications
You must be signed in to change notification settings - Fork 1
/
wait_groups.go
31 lines (28 loc) · 923 Bytes
/
wait_groups.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// To wait for multiple goroutines to finish, we can use a wait group.
package main
import (
"fmt"
"sync"
"time"
)
// This is the function we’ll run in every goroutine.
// Note that a WaitGroup must be passed to functions by pointer or we can use them as global variable.
func worker(id int, wg *sync.WaitGroup) {
// On return, notify the WaitGroup that we’re done.
defer wg.Done()
fmt.Printf("Worker %d starting\n", id)
// Sleep to simulate an expensive task.
time.Sleep(time.Second)
fmt.Printf("Worker %d done\n", id)
}
func main() {
//This WaitGroup is used to wait for all the goroutines launched here to finish.
var wg sync.WaitGroup
//Launch several goroutines and increment the WaitGroup counter for each.
for i := 1; i <= 5; i++ {
wg.Add(1)
go worker(i, &wg)
}
// Block until the WaitGroup counter goes back to 0; all the workers notified they’re done.
wg.Wait()
}