Files
notes_estom/Go/DesignPattern/single/single_test.go
2021-09-03 05:34:34 +08:00

46 lines
767 B
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* @Author:zhoutao
* @Date:2020/12/13 上午10:48
* @Desc:
*/
package single
import (
"sync"
"testing"
)
const parCount = 100
func TestSingleton(t *testing.T) {
ins1 := GetInstance()
ins2 := GetInstance()
if ins1 != ins2 {
t.Fatal("instance is not equal")
}
}
func TestParalleSingleton(t *testing.T) {
start := make(chan struct{})
wg := sync.WaitGroup{}
wg.Add(parCount)
instances := [parCount]*Singleton{}
for i := 0; i < parCount; i++ {
go func(index int) {
//等待channel的关闭信号
<-start
instances[index] = GetInstance()
wg.Done()
}(i)
}
//关闭channel发送关闭信号
close(start)
wg.Wait()
for i := 1; i < parCount; i++ {
if instances[i] != instances[i-1] {
t.Fatal("instance is not equal")
}
}
}