-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathexample_test.go
75 lines (59 loc) · 1.36 KB
/
example_test.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package semgroup_test
import (
"context"
"errors"
"fmt"
"sync"
"github.com/fatih/semgroup"
)
// This example increases a counter for each visit concurrently, using a
// SemGroup to block until all the visitors have finished. It only runs 2 tasks
// at any time.
func ExampleGroup_parallel() {
const maxWorkers = 2
s := semgroup.NewGroup(context.Background(), maxWorkers)
var (
counter int
mu sync.Mutex // protects visits
)
visitors := []int{5, 2, 10, 8, 9, 3, 1}
for _, v := range visitors {
v := v
s.Go(func() error {
mu.Lock()
counter += v
mu.Unlock()
return nil
})
}
// Wait for all visits to complete. Any errors are accumulated.
if err := s.Wait(); err != nil {
fmt.Println(err)
}
fmt.Printf("Counter: %d", counter)
// Output:
// Counter: 38
}
func ExampleGroup_withErrors() {
const maxWorkers = 2
s := semgroup.NewGroup(context.Background(), maxWorkers)
visitors := []int{1, 1, 1, 1, 2, 2, 1, 1, 2}
for _, v := range visitors {
v := v
s.Go(func() error {
if v != 1 {
return errors.New("only one visitor is allowed")
}
return nil
})
}
// Wait for all visits to complete. Any errors are accumulated.
if err := s.Wait(); err != nil {
fmt.Println(err)
}
// Output:
// 3 error(s) occurred:
// * only one visitor is allowed
// * only one visitor is allowed
// * only one visitor is allowed
}