-
Notifications
You must be signed in to change notification settings - Fork 35
/
parallel_test.go
99 lines (92 loc) · 1.74 KB
/
parallel_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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// Copyright 2017 The go-hep Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package parallel_test
import (
"sort"
"sync"
"testing"
"time"
"go-hep.org/x/hep/fwk/utils/parallel"
)
func TestParallelMaxPar(t *testing.T) {
const (
totalDo = 10
maxPar = 3
)
var mu sync.Mutex
max := 0
n := 0
tot := 0
r := parallel.NewRun(maxPar)
for i := 0; i < totalDo; i++ {
r.Do(func() error {
mu.Lock()
tot++
n++
if n > max {
max = n
}
mu.Unlock()
time.Sleep(0.1e9)
mu.Lock()
n--
mu.Unlock()
return nil
})
}
err := r.Wait()
if n != 0 {
t.Errorf("%d functions still running", n)
}
if tot != totalDo {
t.Errorf("all functions not executed; want %d got %d", totalDo, tot)
}
if err != nil {
t.Errorf("wrong error; want nil got %v", err)
}
if max != maxPar {
t.Errorf("wrong number of do's ran at once; want %d got %d", maxPar, max)
}
}
type intError int
func (intError) Error() string {
return "error"
}
func TestParallelError(t *testing.T) {
const (
totalDo = 10
errDo = 5
)
r := parallel.NewRun(6)
for i := 0; i < totalDo; i++ {
i := i
if i >= errDo {
r.Do(func() error {
return intError(i)
})
} else {
r.Do(func() error {
return nil
})
}
}
err := r.Wait()
if err == nil {
t.Fatalf("expected error, got none")
}
errs := err.(parallel.Errors)
if len(errs) != totalDo-errDo {
t.Fatalf("wrong error count; want %d got %d", len(errs), totalDo-errDo)
}
ints := make([]int, len(errs))
for i, err := range errs {
ints[i] = int(err.(intError))
}
sort.Ints(ints)
for i, n := range ints {
if n != i+errDo {
t.Errorf("unexpected error value; want %d got %d", i+errDo, n)
}
}
}