cmpxchg example for 64 bit integer

前端 未结 4 1096
旧时难觅i
旧时难觅i 2020-12-30 16:21

I am using cmpxchg (compare-and-exchange) in i686 architecture for 32 bit compare and swap as follows.

(Editor\'s note: the original 32-bit example was buggy, but th

4条回答
  •  旧时难觅i
    2020-12-30 17:04

    The x86_64 instruction set has the cmpxchgq (q for quadword) instruction for 8-byte (64 bit) compare and swap.

    There's also a cmpxchg8b instruction which will work on 8-byte quantities but it's more complex to set up, needing you to use edx:eax and ecx:ebx rather than the more natural 64-bit rax. The reason this exists almost certainly has to do with the fact Intel needed 64-bit compare-and-swap operations long before x86_64 came along. It still exists in 64-bit mode, but is no longer the only option.

    But, as stated, cmpxchgq is probably the better option for 64-bit code.


    If you need to cmpxchg a 16 byte object, the 64-bit version of cmpxchg8b is cmpxchg16b. It was missing from the very earliest AMD64 CPUs, so compilers won't generate it for std::atomic::compare_exchange on 16B objects unless you enable -mcx16 (for gcc). Assemblers will assemble it, though, but beware that your binary won't run on the earliest K8 CPUs. (This only applies to cmpxchg16b, not to cmpxchg8b in 64-bit mode, or to cmpxchgq).

提交回复
热议问题