Golang: when there's only one writer change the value using atomic.StoreInt32, is it necessary to use atomic.LoadInt32 in the multiple readers?

huangapple go评论84阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2016年12月22日 14:55:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/41277379.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定