-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherrgroupsem_test.go
70 lines (59 loc) · 1.38 KB
/
errgroupsem_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
package errgroupsem_test
import (
"context"
"fmt"
"math/rand"
"runtime"
"testing"
"time"
"github.com/cboudereau/errgroupsem"
"github.com/stretchr/testify/require"
)
func TestErrGroupSem(t *testing.T) {
g, ctx := errgroupsem.WithContext(context.Background(), 10)
start := time.Now()
for i := 0; i < 100; i++ {
g.Go(ctx, func() error {
time.Sleep(1 * time.Millisecond)
return nil
})
}
err := g.Wait()
elapsed := time.Since(start)
require.NoError(t, err)
require.LessOrEqual(t, elapsed, 20*time.Millisecond)
require.GreaterOrEqual(t, elapsed, 5*time.Millisecond)
}
func TestFanInFanOutExample(t *testing.T) {
ctx := context.Background()
numCPU := runtime.NumCPU()
g, ctx := errgroupsem.WithContext(ctx, numCPU)
producer := func(size int) <-chan string {
output := make(chan string)
g.Go(ctx, func() error {
defer close(output)
wg, ctx := errgroupsem.WithContext(ctx, numCPU)
for i := 0; i < size; i++ {
i := i //golang closure issue
wg.Go(ctx, func() error {
s := int64(rand.Intn(100))
time.Sleep(time.Millisecond * time.Duration(s))
output <- fmt.Sprintf("%v/%vms", i, s)
return nil
})
}
return wg.Wait()
})
return output
}
consumer := func(input <-chan string) {
g.Go(ctx, func() error {
for x := range input {
fmt.Println("consumer", x)
}
return nil
})
}
consumer(producer(100))
g.Wait()
}