一、代码实现
import ( "fmt" "sync" "testing" "unsafe" ) type Singleton struct { } var singLeInstance *Singleton var once sync.Once //单例模式 func GetSingletonObj() *Singleton { //仅运行一次 once.Do(func() { fmt.Println("Create Obj") singLeInstance = new(Singleton) }) return singLeInstance } func TestGetSingletonObj(t *testing.T) { var wg sync.WaitGroup for i := 0; i < 10; i++ { wg.Add(1) go func() { obj := GetSingletonObj() fmt.Printf("%x\n", unsafe.Pointer(obj)) wg.Done() }() } wg.Wait() }
=== RUN TestGetSingletonObj Create Obj 4beac8 4beac8 4beac8 4beac8 4beac8 4beac8 4beac8 4beac8 4beac8 4beac8 --- PASS: TestGetSingletonObj (0.00s) PASS