在阅读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()
}
}
为什么是 ataomic.StoreUint32
使用,而不是说 o.done = 1
?这些不是等价的吗?有什么区别?在弱内存模型的机器上观察到 o.done 设置为 1 之前,我们是否必须使用原子操作(
atomic.StoreUint32
)来确保其他 goroutine 可以观察到“f()”的效果?
最佳答案
请记住,除非您手动编写程序集,否则您不是在针对机器的内存模型进行编程,而是针对 Go 的内存模型进行编程。这意味着即使原始分配对于您的架构是原子的,Go 也需要使用 atomic 包来确保所有支持的架构的正确性。
访问 done
互斥锁之外的标志只需要安全,而不是严格排序,因此可以使用原子操作而不是总是使用互斥锁获取锁。这是使快速路径尽可能高效的优化,允许 sync.Once
用于热路径。
用于 doSlow
的互斥锁仅用于该函数内的互斥,以确保只有一个调用者到达 f()
之前done
标志已设置。该标志是使用 atomic.StoreUint32
编写的,因为它可能与 atomic.LoadUint32
同时发生在互斥锁保护的临界区之外。
阅读done
字段与写入并发,甚至是原子写入,是一种数据竞争。仅仅因为该字段是原子读取的,并不意味着您可以使用正常赋值来写入它,因此首先使用 atomic.LoadUint32
检查标志。并写成 atomic.StoreUint32
done
的直读内doSlow
是安全的,因为它受到互斥锁的并发写入保护。与 atomic.LoadUint32
同时读取值是安全的,因为两者都是读取操作。
关于go - 为什么 atomic.StoreUint32 优于 sync.Once 中的正常分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65935091/