dongsu1539
2017-10-04 04:07
浏览 570
已采纳

Golang atomic.LoadUint32是否必要?

Golang's atomic package provides function func LoadUint32(addr *uint32) (val uint32). I looked into the assembly implementation:

TEXT ·LoadUint32(SB),NOSPLIT,$0-12
MOVQ    addr+0(FP), AX
MOVL    0(AX), AX
MOVL    AX, val+8(FP)
RET

which basically load the value from the memory address and return it. I'm wondering if we have a uint32 pointer(addr) x, what is the difference between calling atomic.LoadUint32(x) and directly access it using *x?

图片转代码服务由CSDN问答提供 功能建议

Golang的原子包提供函数 func LoadUint32(addr * uint32)(val uint32)。 我调查了汇编实现:

  TEXT·LoadUint32(SB),NOSPLIT,$ 0-12 
MOVQ addr + 0(FP),AX 
MOVL 0(AX),  AX 
MOVL AX,val + 8(FP)
RET 
   
 
 

基本上是从内存地址加载值并返回它。 我想知道我们是否 有一个uint32指针(addr) x ,调用 atomic.LoadUint32(x)和使用 * x 直接访问它有什么区别?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongxi2014 2017-10-04 04:34
    已采纳

    which basically load the value from the memory address and return it.

    That is the case in your context, but might differ on a different machine architecture where atomicity is to be implemented, as discussed here.
    As mentioned in go issue 8739

    We intrinsify both sync/atomic and runtime/internal/atomic for a bunch of architectures.
    The APIs are not unified (e.g. LoadUint32 in sync/atomic is Load in runtime/internal/atomic).

    (* "intrinsify" as in issue 4947)

    As mentioned in my first link:

    Regarding loads and stores.

    Memory model along with instruction set specifies whether plain loads and stores are atomic or not. Typical guarantee for all modern commodity hardware is that aligned word-sized loads and stores are atomic. For example, on x86 architecture (IA-32 and Intel 64) 1-, 2-, 4-, 8- and 16-byte aligned loads and stores are all atomic (that is, plain MOV instruction, MOVQ and MOVDQA are atomic).

    点赞 打赏 评论

相关推荐 更多相似问题