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
| package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
func worker(id int) {
fmt.Printf("Worker %d starting at %s\n", id, time.Now())
time.Sleep(time.Duration(rand.Intn(3)) * time.Second)
fmt.Printf("Worker %d done at %s\n", id, time.Now())
}
func main() {
var wg sync.WaitGroup
for i := 1; i <= 5; i++ {
wg.Add(1)
i := i
go func() {
defer wg.Done()
worker(i)
}()
}
wg.Wait()
}
|