-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworkerpool_test.go
60 lines (47 loc) · 1.04 KB
/
workerpool_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
package workerpool
import (
"sync"
"testing"
"time"
)
func TestConcurrency(t *testing.T) {
concurrency := 10
numTasks := concurrency * 2
perceivedConcurrency := 0
maxConcurrency := 0
invocations := 0
var rwlock sync.RWMutex
p := NewWorkerPool(concurrency, 100, numTasks)
for i := 0; i < numTasks; i++ {
p.AddTask(func() error {
rwlock.Lock()
invocations++
perceivedConcurrency++
if perceivedConcurrency > maxConcurrency {
maxConcurrency = perceivedConcurrency
}
rwlock.Unlock()
// Process our "task"
time.Sleep(250 * time.Millisecond)
rwlock.Lock()
perceivedConcurrency--
rwlock.Unlock()
return nil
})
}
// Read all results
for i := 0; i < numTasks; i++ {
res := <-p.GetResultsChannel()
if res.Error != nil {
t.Errorf("task failed unexpectedly")
}
}
p.WaitAll()
p.Close()
if invocations != numTasks {
t.Errorf("incorrect number of invocations: %v", invocations)
}
if maxConcurrency != concurrency {
t.Errorf("concurrency differed from specified: %v", maxConcurrency)
}
}