登录
首页 >  Golang >  Go问答

为什么使用atomic.StoreUint32比普通分配要更流行在sync.Once中使用?

来源:stackoverflow

时间:2024-02-16 22:57:24 212浏览 收藏

从现在开始,我们要努力学习啦!今天我给大家带来《为什么使用atomic.StoreUint32比普通分配要更流行在sync.Once中使用?》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!

问题内容

在阅读go源码时,我对src/sync/once.go中的代码有一个疑问:

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()
    }
}

为什么使用 atomic.storeuint32,而不是 o.done = 1?这些不是等价的吗?有什么区别?

在内存模型较弱的机器上,在 o.done 设置为 1 之前,我们是否必须使用原子操作(atomic.storeuint32)来确保其他 goroutine 可以观察到 f() 的效果?


解决方案


请记住,除非您手动编写程序集,否则您不是针对机器的内存模型进行编程,而是针对 Go 的内存模型进行编程。这意味着即使原始赋值对于您的架构来说是原子的,Go 也需要使用原子包来确保所有支持的架构的正确性。

在互斥体之外访问 done 标志只需要安全,不需要严格排序,因此可以使用原子操作,而不是总是用互斥体获取锁。这是一种使快速路径尽可能高效的优化,允许在热路径中使用 sync.Once

用于 doSlow 的互斥体仅用于该函数内的互斥,以确保在设置 done 标志之前只有一个调用者能够访问 f()。该标志是使用 atomic.StoreUint32 编写的,因为它可能与互斥锁保护的临界区之外的 atomic.LoadUint32 同时发生。

在写入(甚至是原子写入)的同时读取 done 字段是一种数据竞争。仅仅因为该字段是原子读取的,并不意味着您可以使用正常赋值来写入它,因此首先使用 atomic.LoadUint32 检查该标志,并使用 atomic.StoreUint32 写入

doSlow 中直接读取 done 是安全的,因为它受到互斥体的并发写入保护。与 atomic.LoadUint32 同时读取值是安全的,因为两者都是读取操作。

以上就是《为什么使用atomic.StoreUint32比普通分配要更流行在sync.Once中使用?》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>