用法golang atomic LoadInt32 / StoreInt32(64) [英] usage golang atomic LoadInt32/StoreInt32 (64)

查看:2516
本文介绍了用法golang atomic LoadInt32 / StoreInt32(64)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以显示需要使用这种原子操作的例子。

  importsync / atomic

...
var sharedA int64
var sharedB * int64
...
//和解代码
tmpVarA:= sharedA
tmpVarB:= * sharedB
//和
tmpVarA:= atomic.LoadInt64(& sharedA)
tmpVarB:= atomic.LoadInt64(sharedB)


解决方案

它根本没有记录在软件包中,但通常原子的加载和正常值的存储不存在原子性,因为CPU操作已经是原子的,但为了订购。如果您使用原子操作,则语言规范或CPU指令文档为您提供了有关CPU以哪种顺序存储另一个CPU将看到的某些保证。大多数现代CPU没有这样的保证,如果你不使用适当的(昂贵的)指令。



所以在你的例子中(我假设,如果共享变量已经被goroutine首先写入 sharedA ,然后 sharedB ,那么读取时如果没有原子操作,您可能会看到 sharedB 的更改值,仍旧是 sharedA 的旧值。如果存储或加载需要额外的魔法才能获得订购权,那么在不同的CPU系列上会有所不同,所以通常情况下,语言使您对存储和加载都使用原子函数,然后编译器/库知道您的实际CPU需求。 p>

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


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.

So in your example (I assume, since the package isn't documented), if the shared variables have been written by a goroutine first to sharedA, then sharedB, when reading then without atomic operations you might see the changed value of sharedB and still the old value of sharedA. It's different on different CPU families if the stores or loads need to perform extra magic to get the ordering right, so usually languages make you use atomic functions for both stores and loads and then the compiler/library knows what your actual CPU needs.

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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆