go once仅且执行一次

最近看到用csdn友发了一篇关于 go的sync.Once的分析,自己看了两遍才弄明白其设计。废话少说咱走起!!!

暂且不说项目需要用到的场景,我们就纯粹学习下人家是怎么设计的。

func main(){	
    myOnce := sync.Once{}
	myOnce.Do(doSomething)
}


func doSomething(){
	fmt.Println("im doing things")
}

直接进入Do方法,看看他是如何保证多线程且生命周期内仅执行一次的。

type Once struct {
	// done indicates whether the action has been performed.
	// It is first in the struct because it is used in the hot path.
	// The hot path is inlined at every call site.
	// Placing done first allows more compact instructions on some architectures (amd64/x86),
	// and fewer instructions (to calculate offset) on other architectures.
	done uint32
	m    Mutex
}

func (o *Once) Do(f func()) {
	// Note: Here is an incorrect implementation of Do:
	//
	//	if atomic.CompareAndSwapUint32(&o.done, 0, 1) {
	//		f()
	//	}
	//
	// Do guarantees that when it returns, f has finished.
	// This implementation would not implement that guarantee:
	// given two simultaneous calls, the winner of the cas would
	// call f, and the second would return immediately, without
	// waiting for the first's call to f to complete.
	// This is why the slow path falls back to a mutex, and why
	// the atomic.StoreUint32 must be delayed until after f returns.

	if atomic.LoadUint32(&o.done) == 0 {
		// Outlined slow-path to allow inlining of the fast-path.
		o.doSlow(f)
	}
}

func (o *Once) doSlow(f func()) {
	o.m.Lock()
	defer o.m.Unlock()
	if o.done == 0 {
		defer atomic.StoreUint32(&o.done, 1)
		f()
	}
}

once 定义加了一个Mutex 互斥锁,好接着看 do函数,官方直接提出了一种错误的做法,来看下    

 if atomic.CompareAndSwapUint32(&o.done, 0, 1) {
     f()
} 这有可不妥呢? 来看,如果有多个goroutine同事执行我的main文件中的 myOnce.Do(doSomething),根据atomic的CompareAndSwapUint32 实现原理我们知道,他是原子性的,即他可以确保同时只有一个操作在执行交换操作,无论你是多cpu还是多线程,因为这个函数的底层是直接通过缓存器来比对在做交换的,所以并发情况下只会有一个操作能进入f()执行,其他都直接跳过直接返回,直接返回的话就会出现一种情况,那就是f还没有执行完其他线程已经开始往下执行了,假如你这个f执行的是加载配置文件,那么后面执行操作如果依赖于这个配置,岂不是就出问题了,因为配置还没有加载完成呢。所以官方就指出了这种错误的做法给我们看。

 

好,那么我们再来看,他是如何保证所有goroutine都等待其中一个执行完然后才进行往下的操作的呢。   atomic.LoadUint32(&o.done) == 0 先通过load方法来加载o.done变量,有人就说为啥不直接判断呢 o.done == 0 那是因为如果这样子做,其实按理说是可以的,然后就进入 doSlow ,进入doSlow 后就开始竞争锁了,由于是互斥锁,所以只有一个goroutine能拿到该锁,其他携程都被挂起等待,里面又判断了一次 o.done是怕进去doSlow后有携程已经执行完f了,所以在做了一次判定。如果拿到锁后 o.done 确定是0 那么就可以安全进行执行f了,因为此时能拿到锁的只有一个goroutine,最后通过defer 先进后出的规则把 o.done设置为1 再释放锁,从而其他所有携程就可以获取锁,进入o.done判断,由于o.done已经为1了,所以后面每一个goroutine逐个返回,不再执行f,从而保证仅当f执行完后,才能往下执行,而且保证f仅被执行一次。这设计其实很多单例模式都使用,只是我们平时很少用到这种设计。

 

完!!!!!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值