2020-04-21 17:50:21 +03:00
|
|
|
|
package singleton
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"sync"
|
|
|
|
|
"testing"
|
|
|
|
|
)
|
|
|
|
|
|
2020-04-23 04:47:58 +03:00
|
|
|
|
const workerCount = 500
|
2020-04-21 17:50:21 +03:00
|
|
|
|
|
2020-04-23 04:47:58 +03:00
|
|
|
|
func TestWorkerSingleton(t *testing.T) {
|
|
|
|
|
ins1 := GetWorkerInstance()
|
|
|
|
|
ins2 := GetWorkerInstance()
|
2020-04-21 17:50:21 +03:00
|
|
|
|
if ins1 != ins2 {
|
2020-04-23 04:47:58 +03:00
|
|
|
|
t.Fatal("worker(instance) is not exactly the same")
|
2020-04-21 17:50:21 +03:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-04-23 04:47:58 +03:00
|
|
|
|
// 获取500次,Worker 是否总是同一个worker
|
|
|
|
|
func TestParallelWorkerSingleton(t *testing.T) {
|
2020-04-21 17:50:21 +03:00
|
|
|
|
wg := sync.WaitGroup{}
|
2020-04-23 04:47:58 +03:00
|
|
|
|
wg.Add(workerCount)
|
|
|
|
|
instances := [workerCount]*Worker{}
|
|
|
|
|
for i := 0; i < workerCount; i++ {
|
2020-04-21 17:50:21 +03:00
|
|
|
|
go func(index int) {
|
2020-04-23 04:47:58 +03:00
|
|
|
|
instances[index] = GetWorkerInstance()
|
2020-04-21 17:50:21 +03:00
|
|
|
|
wg.Done()
|
|
|
|
|
}(i)
|
|
|
|
|
}
|
|
|
|
|
wg.Wait()
|
2020-04-23 04:47:58 +03:00
|
|
|
|
for i := 1; i < workerCount; i++ {
|
2020-04-21 17:50:21 +03:00
|
|
|
|
if instances[i] != instances[i-1] {
|
2020-04-23 04:47:58 +03:00
|
|
|
|
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")
|
2020-04-21 17:50:21 +03:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|