【Duke】只运行一次 028 - PingPongGooo/GoFoundation GitHub Wiki

仅执行一次

单例模式(懒汉式,线程安全)

var once sync.Once
var obj*SingletonObj

func GetSingletonObj() *SingletonObj{
   once.Do(func(){
       fmt.Println("Create Singleton obj.")
       obj = &SingletonObj{}
   })
}

package singleton

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 TestGetSingleObj(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()
}