Golang sync.Once 简介与用法

在这里插入图片描述

1.简介

sync.Once用来保证函数只执行一次。要达到这个效果,需要做到两点:
(1)计数器,统计函数执行次数;
(2)线程安全,保障在多 Go 程的情况下,函数仍然只执行一次,比如锁。

import (
   "sync/atomic"
)

// Once is an object that will perform exactly one action.
type Once struct {
   m    Mutex
   done uint32
}

Once 结构体证明了之前的猜想,果然有两个变量。

// Do calls the function f if and only if Do is being called for the
// first time for this instance of Once. In other words, given
//     var once Once
// if once.Do(f) is called multiple times, only the first call will invoke f,
// even if f has a different value in each invocation. A new instance of
// Once is required for each function to execute.
//
// Do is intended for initialization that must be run exactly once. Since f
// is niladic, it may be necessary to use a function literal to capture the
// arguments to a function to be invoked by Do:
//     config.once.Do(func() { config.init(filename) })
//
// Because no call to Do returns until the one call to f returns, if f causes
// Do to be called, it will deadlock.
//
// If f panics, Do considers it to have returned; future calls of Do return
// without calling f.
//
func (o *Once) Do(f func()) {
   if atomic.LoadUint32(&o.done) == 1 {
      return
   }
   // Slow-path.
   o.m.Lock()
   defer o.m.Unlock()
   if o.done == 0 {
      defer atomic.StoreUint32(&o.done, 1)
      f()
   }
}

Do 方法相当简单,但也有可以学习的地方。比如一些标志位可以通过原子操作表示,避免加锁,提高性能。

Do 方法实现过程如下:
(1)首先通过原子load函数获取执行次数,如果已经执行过了则 return;
(2)lock;
(3)执行函数;
(4)原子 store 函数执行次数 1;
(5)unlock。

下面看一个示例。

package main

import (
	"fmt"
	"sync"
	"time"
)

var once sync.Once
var onceBody = func() {
    fmt.Println("Only once")
}

func main() {
	for i := 0; i < 5; i++ {
		go func(i int) {
			once.Do(onceBody)
			fmt.Println("i=",i)
		}(i)
	}
	time.Sleep(time.Second) // 睡眠 1s 等待 go 程执行完,注意睡眠时间不能太短。
}

程序运行输出:

Only once
i= 3
i= 4
i= 0
i= 1
i= 2

从输出结果可以看出,尽管 for 循环每次都会调用 once.Do() 方法,但是函数 onceBody() 却只会被执行一次。

2.延迟初始化

利用 sync.Once 只执行一次的特性,可以轻松实现延迟初始化。

有些初始化操作,如果不希望程序在一开始的时候就被执行的时候,我们可以使用 sync.Once 在需要的时候才进行初始化。

比如 get 一个客户端对象。

type MyClient struct{}

var once sync.Once
var myCli *MyClient

func getMyClient() *MyClient {
	once.Do(func() {
		myCli = new(MyClient)
	})
	return myCli
}

在需要获取 MyClient 的对象时,不需要在程序在一开始的时候去初始化,而是在真正使用的时候直接调用 getMyClient 函数即可获取。

聪明的你可能已经发现,上面的初始化写法实际上是 Go 单例模式的一种实现方式。

参考文献

简书.Go语言——sync.Once分析
Package sync.Go 编程语言官网

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值