Go:sync.Once 实现单例模式

代码:

package main

import (
    "fmt"
    "sync"
)

type Singleton struct{}

var singleton *Singleton
var once sync.Once

func GetSingletonObj() *Singleton {
    once.Do(func() {
        fmt.Println("Create Obj")
        singleton = new(Singleton)
    })
    return singleton
}

func main() {
    var wg sync.WaitGroup
    for i := 0; i < 5; i++ {
        wg.Add(1)
        go func() {
            obj := GetSingletonObj()
            fmt.Printf("%p\n", obj)
            wg.Done()
        }()
    }
    wg.Wait()
}
View Code

输出结果:

转载于:https://www.cnblogs.com/believepd/p/11047229.html

猜你喜欢

转载自blog.csdn.net/weixin_33751566/article/details/93338629
今日推荐