单例的实现依赖 sync.Once 中的 Do 函数,因为每个 sync.Once 类型变量中的 Do 函数永远只会执行一次。
package main
import (
"fmt"
"sync"
"time"
"unsafe"
)
func main() {
for i := 0; i < 10; i++ {
go func() {
user := getUser()
user2 := getUser2()
fmt.Printf("user address: %x\n", unsafe.Pointer(user))
fmt.Printf("user2 address: %x\n", unsafe.Pointer(user2))
}()
}
time.Sleep(time.Millisecond)
}
type User struct {
}
type User2 struct {
}
var (
userInstance *User
user2Instance *User2
userOnce sync.Once
)
func getUser() *User {
userOnce.Do(func() {
userInstance = new(User)
})
return userInstance
}
func getUser2() *User2 {
// 变量userOnce的Do函数只会执行一次,所以user2Instance永远不会被初始化
userOnce.Do(func() {
user2Instance = new(User2)
})
// 永远返回nil
return user2Instance
}