英文:
Golang: when there's only one writer change the value using atomic.StoreInt32, is it necessary to use atomic.LoadInt32 in the multiple readers?
问题
正如标题所说。
基本上我想知道的是,在写入时,atomic.StoreInt32是否也会锁定读取操作?
另一个相关的问题是:atomic.StoreUint64(&procRate, procCount)
和atomic.StoreUint64(&procRate, atomic.LoadUint64(&procCount))
是否等效?
提前感谢。
英文:
As the title says.
basically what I'm wondering is that will the atomic.StoreInt32 also lock read operation while it's writing?
Another relative question:, is atomic.StoreUint64(&procRate, procCount)
equivalent to atomic.StoreUint64(&procRate, atomic.LoadUint64(&procCount))
?
Thanks in advance.
答案1
得分: 1
是的,当你同时加载和存储相同的值时,你需要使用原子操作。竞争检测器应该会对此发出警告。
至于第二个问题,如果procCount
值也在并发使用中,那么你仍然需要使用原子操作来加载它。下面这两种方式是不等价的:
atomic.StoreUint64(&procRate, procCount)
atomic.StoreUint64(&procRate, atomic.LoadUint64(&procCount))
前者直接读取procCount
并将其传递给StoreUint64
,而后者通过LoadUint64
安全地获取副本后再传递。
英文:
Yes, you need to use atomic operations when you are both loading and storing the same value. The race detector should warn you about this.
As for the second question, if the procCount
value is also being used concurrently, then you still need to load it using an atomic operation. These two are not equivalent:
atomic.StoreUint64(&procRate, procCount)
atomic.StoreUint64(&procRate, atomic.LoadUint64(&procCount))
The former reads procCount
directly to pass to StoreUint64
, while the latter passes a copy safely obtained via LoadUint64
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论