-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
61 lines (49 loc) · 1.14 KB
/
main.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
49
50
51
52
53
54
55
56
57
58
59
60
61
package main
import (
"fmt"
"sync"
"time"
)
func main() {
runLoop(4, 20)
}
func runLoop(concurrency int, items int) int {
fmt.Printf("running jobs: %d, concurrency: %d\n", items, concurrency)
// Waitgroup for all goroutines to finish
var wg sync.WaitGroup
// Holds any errors returned, protected by errLock Mutex
errs := make([]error, 0)
var errLock sync.Mutex
// Buffered channel
semaphore := make(chan int, concurrency)
// Work loop
for i := 0; i < items; i++ {
// Start the goroutines that will do the work
wg.Add(1)
go func(loop int) {
defer wg.Done()
semaphore <- 1
fmt.Printf("running loop: %d\n", loop)
// Simulate some work
time.Sleep(time.Duration(2) * time.Second)
if err := fmt.Errorf("error on loop: %d", loop); err != nil {
// Add to errors
errLock.Lock()
defer errLock.Unlock()
errs = append(errs, err)
}
// Read out of the channel to free up another goroutine
<-semaphore
}(i)
}
wg.Wait()
if len(errs) > 0 {
// Report, or deal with errs
fmt.Printf("\n%d errors occurred:\n", len(errs))
for _, err := range errs {
fmt.Printf("%s\n", err)
}
return 1
}
return 0
}