-
Notifications
You must be signed in to change notification settings - Fork 20
/
worker.go
48 lines (36 loc) · 789 Bytes
/
worker.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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package main
import (
"fmt"
"sync"
"time"
)
func main() {
start := time.Now()
defer func() {
fmt.Println(time.Since(start))
}()
// Set the max concurrency to 5
maxConcurrency := 3
// Use a buffered channel to simulate semaphore.
sem := make(chan struct{}, maxConcurrency)
nTasks := 10
var wg sync.WaitGroup
for i := 0; i < nTasks; i++ {
// Acquire the semaphore. This will block once it is full.
// This will prevent spawning too many goroutines.
sem <- struct{}{}
wg.Add(1)
go func(i int) {
defer wg.Done()
defer func() {
// Release the semaphore once it is done.
<-sem
fmt.Println("done work", i)
}()
fmt.Println("performing work:", i)
time.Sleep(1 * time.Second)
}(i)
}
wg.Wait()
fmt.Println("program terminating")
}