同步/ atomic.once.go中的两个原子样式代码是否必需? [英] Is the two atomic style code in sync/atomic.once.go necessary?

查看:105
本文介绍了同步/ atomic.once.go中的两个原子样式代码是否必需?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

同步/ atomic.once.go中的代码是:

  func(o * Once)Do(f func )){
如果atomic.LoadUint32(& o.done)== 1 {// A
// if o.done == 1 {
return
}
//慢速路径。
omLock()
推迟omUnlock()
如果o.done == 0 {
f()
atomic.CompareAndSwapUint32(& o.done,0 ,1)// B
//o.done = 1
}
}

我不认为上面两个'原子风格'的代码A,B是必要的或有用的。
我认为这个锁已经足够了,如果A,B不是原子风格的话就可以。
我必须错过什么,请善意告诉我代码A,B的目的。
谢谢。

解决方案

The original 是正确的。原因是Go 内存模型说,没有同步( if o。 done == 1 )可能根本不会观察到对o.done的更改。


The code in sync/atomic.once.go is :

func (o *Once) Do(f func()) {
        if atomic.LoadUint32(&o.done) == 1 { //A
        //if o.done == 1 {
            return
        }
        // Slow-path.
        o.m.Lock()
        defer o.m.Unlock()
        if o.done == 0 {
            f()
            atomic.CompareAndSwapUint32(&o.done, 0, 1) //B
            //o.done = 1
        }
    }

I don't think the two 'atomic-style' code A,B above is necessary or useful. I think the lock is enough, and it could be ok if A,B are not atomic style. I must miss something, please be kind to tell me the purpose of the code A,B. Thank you.

解决方案

The original is correct. The reason is that the Go Memory Model says, that without synchronization (if o.done == 1) the changes to o.done might not be observed at all.

这篇关于同步/ atomic.once.go中的两个原子样式代码是否必需?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆