sync.Once单例

sync.Once单例

在编程的很多场景下我们需要确保某些操作在高并发的场景下只执行一次,例如只加载一次配置文件、只关闭一次通道等。

Go语言中的sync包中提供了一个针对只执行一次场景的解决方案–sync.Once

sync.Once只有一个Do方法,其签名如下:

func (o *Once) Do(f func()) {} 

注意:如果要执行的函数f需要传递参数就需要搭配闭包来使用。

方式一:once.Do

package main
import (
	"fmt"
	"sync"
)
var once sync.Once
var person *Person
type Person struct {
	Name string
}

func NewPerson(name string)*Person {
	once.Do(func() {
		person = new(Person)
		person.Name = name
	})
	return person
}

func main() {
	//p1 := &Person{Name:"hallen1"}
	//p2 := &Person{Name:"hallen2"}
	//fmt.Printf("%p\n",p1)  //0x14000110220
	//fmt.Printf("%p\n",p2)  // 0x14000110230
	
	p1 := NewPerson("hallen1") 
	p2 := NewPerson("hallen2") 
	fmt.Printf("%p\n",p1)  // 0x14000010240
	fmt.Printf("%p\n",p2)  // 0x14000010240
}

方式二:once.Do只执行一次

package main

import (
	"fmt"
	"sync"
)

var (
	once sync.Once
)

func main() {
	for i := 0; i < 10; i++ {
		once.Do(test)
	}

}

func test() {
	fmt.Println("111")
}
posted @ 2021-08-16 16:06  Jeff的技术栈  阅读(231)  评论(0编辑  收藏  举报
回顶部