-
Notifications
You must be signed in to change notification settings - Fork 23
/
singleton_test.go
62 lines (56 loc) · 1.31 KB
/
singleton_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
package singleton
import (
"sync"
"testing"
)
const workerCount = 500
func TestWorkerSingleton(t *testing.T) {
ins1 := GetWorkerInstance()
ins2 := GetWorkerInstance()
if ins1 != ins2 {
t.Fatal("worker(instance) is not exactly the same")
}
}
// 获取500次,Worker 是否总是同一个worker
func TestParallelWorkerSingleton(t *testing.T) {
wg := sync.WaitGroup{}
wg.Add(workerCount)
instances := [workerCount]*Worker{}
for i := 0; i < workerCount; i++ {
go func(index int) {
instances[index] = GetWorkerInstance()
wg.Done()
}(i)
}
wg.Wait()
for i := 1; i < workerCount; i++ {
if instances[i] != instances[i-1] {
t.Fatal("Worker instance is not equal")
}
}
}
func TestManagerSingleton(t *testing.T) {
ins1 := GetManagerInstance()
ins2 := GetManagerInstance()
if ins1 != ins2 {
t.Fatal("Manager(instance) is not exactly the same")
}
}
// 获取500次,Manager 是否总是同一个Manager
func TestParallelManagerSingleton(t *testing.T) {
wg := sync.WaitGroup{}
wg.Add(workerCount)
instances := [workerCount]*Manager{}
for i := 0; i < workerCount; i++ {
go func(index int) {
instances[index] = GetManagerInstance()
wg.Done()
}(i)
}
wg.Wait()
for i := 1; i < workerCount; i++ {
if instances[i] != instances[i-1] {
t.Fatal("Manager instance is not exactly equal")
}
}
}