Skip to content

Commit 5774cb0

Browse files
razertorysenghoo
authored andcommitted
update: 单例模式测试用例改造为并发以验证并发安全
1 parent 514337d commit 5774cb0

File tree

1 file changed

+20
-5
lines changed

1 file changed

+20
-5
lines changed

03_singleton/singleton_test.go

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,26 @@
11
package singleton
22

3-
import "testing"
3+
import (
4+
"sync"
5+
"testing"
6+
)
7+
8+
const count = 100
49

510
func TestSingleton(t *testing.T) {
6-
ins1 := GetInstance()
7-
ins2 := GetInstance()
8-
if ins1 != ins2 {
9-
t.Fatal("instance is not equal")
11+
wg := sync.WaitGroup{}
12+
wg.Add(count)
13+
instances := [count]*Singleton{}
14+
for i := 0; i < count; i++ {
15+
go func(index int) {
16+
instances[index] = GetInstance()
17+
wg.Done()
18+
}(i)
19+
}
20+
wg.Wait()
21+
for i := 1; i < count; i++ {
22+
if instances[i] != instances[i-1] {
23+
t.Fatal("instance is not equal")
24+
}
1025
}
1126
}

0 commit comments

Comments
 (0)