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

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

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

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

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

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
}

相关文章:

  • 2023-01-09
  • 2023-03-20
  • 2021-10-21
  • 2021-10-05
  • 2021-03-09
  • 2021-06-24
猜你喜欢
  • 2023-03-14
  • 2023-03-16
  • 2023-03-20
  • 2022-12-23
  • 2022-03-02
  • 2021-09-16
相关资源
相似解决方案