package main
import (
"fmt"
"sync"
)
type Singleton struct {
}
var singleInstance *Singleton
var once sync.Once
func GetSingletionObj() *Singleton {
once.Do(func() {
fmt.Println("Createa Singleton")
singleInstance = new(Singleton)
})
return singleInstance
}
func main() {
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
obj := GetSingletionObj()
fmt.Printf("%p\n", obj)
wg.Done()
}()
}
wg.Wait()
}
// result:
Createa Singleton
0x1196ab8
0x1196ab8
0x1196ab8
0x1196ab8
0x1196ab8
0x1196ab8
0x1196ab8
0x1196ab8
0x1196ab8
0x1196ab8
网友评论