sharedA  sharedB  sharedB  sharedA 

当然,这个软件包没有记录任何这种情况,所以实际上没有区别,因为我们不知道软件包实际上保证了什么。所以对于所有的实际目的来说都没用。


Can anybody show the example where usage of such atomic operations needed. I don't understand a differenece between

import "sync/atomic"

...
var sharedA int64
var sharedB *int64
...
// concurent code
tmpVarA := sharedA
tmpVarB := *sharedB
// and
tmpVarA := atomic.LoadInt64(&sharedA)
tmpVarB := atomic.LoadInt64(sharedB)

It's not documented in the package at all, but normally atomic loads and stores of normal values are there not for atomicity because the CPU operations are already atomic, but for ordering. The language specification or CPU instruction documentation gives you certain guarantees about in which order one CPU stores will be seen by another CPU if you use the atomic operations. Most modern CPUs have no such guarantees if you don't use the proper (expensive) instructions for it.

sharedAsharedBsharedBsharedA

Of course, the package doesn't document any of this, so in practice there is no difference because we don't know what the package actually guarantees. So for all practical purposes it's useless.

这篇关于用法golang atomic LoadInt32 / StoreInt32(64)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!