-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtaskPool_test.go
81 lines (64 loc) · 1.52 KB
/
taskPool_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
package concurrent
import (
"math/rand"
"sync/atomic"
"testing"
"time"
)
func TestTaskPool(t *testing.T) {
falseCounter := int32(0)
allCounter := int32(0)
taskLimit := 1000000
pool := NewTaskPool(1000, func(i interface{}) {
atomic.AddInt32(&falseCounter, 1)
})
for i := 0; i < taskLimit; i++ {
pool.Submit(func() {
randomTimeMultiplier := rand.Float32() * 10.0
time.Sleep(time.Duration(randomTimeMultiplier) * time.Millisecond)
atomic.AddInt32(&allCounter, 1)
})
}
pool.WaitForAll()
pool.Shutdown()
if falseCounter > 0 {
t.Errorf("False counter is %d", falseCounter)
}
if allCounter != int32(taskLimit) {
t.Errorf("Not all tasks were executed")
}
}
func TestTaskPoolRecursive(t *testing.T) {
falseCounter := int32(0)
allCounter := int32(0)
taskLimit := 100
pool := NewTaskPool(1, func(i interface{}) {
atomic.AddInt32(&falseCounter, 1)
})
var executeTask func(pool *TaskPool)
executeTask = func(pool *TaskPool) {
for i := 0; i < 3; i++ {
pool.Submit(func() {
randomTimeMultiplier := rand.Float32() * 100.0
time.Sleep(time.Duration(randomTimeMultiplier) * time.Millisecond)
ac := int(atomic.AddInt32(&allCounter, 1))
if ac <= taskLimit {
pool.Submit(func() {
executeTask(pool)
})
} else {
atomic.AddInt32(&allCounter, -1)
}
})
}
}
executeTask(pool)
pool.WaitForAll()
pool.Shutdown()
if falseCounter > 0 {
t.Errorf("False counter is %d", falseCounter)
}
if allCounter != int32(taskLimit) {
t.Errorf("Not all tasks were executed")
}
}