0

As I know, 64bit integer work differently by operation system. I could find out that is true in assembly instructions. Below like this.

#include <iostream>

int main()
{
    uint64_t sharedValue = 0;
    sharedValue = 0x100000002;    
}

32bit 64bit

So I thought a 32bit operation system couldn't guarantee the atomicity of the 64bit integer because the operation consists of multiple instructions. But 64bit operation system can.

So I checked the 64-bit integer. To see how atomicity is guaranteed depending on the operating system.

#include <iostream>
#include <atomic>

using namespace std;


int main()
{
    atomic<uint64_t> num;
    cout << boolalpha << num.is_lock_free() << endl;
}

32bit atomicity 64bit atomicity

As I know, 'lock_is_free = true' means this type can be processed atomically in the CPU.

if i understood correctly, why dose a 64bit integer on 32bit os return 'true' by lock_is_free().

Assembly codes are multiple, but some operations can be processed atomicity on CPU??

Please, Answer my problem.

pangpeng
  • 1
  • 1
  • 2
    I just tried with `gcc` and checked the disassembly: `gcc` uses the FPU registers to store a `atomic`. The FPU registers allow atomic 64-bit integer operations. – Martin Rosenau Jan 21 '22 at 12:52
  • Most architectures provide some mechanism for an atomic double-wide compare and swap, which on a 32-bit system would let you compare and swap a 64-bit object. With a CAS loop, that lets you do any kind of atomic read-modify-write on a 64-bit object in a lock-free fashion; in particular you can do a store by just disregarding the old value. It will be at least an order of magnitude slower than an ordinary store instruction, but it's still lock-free. 64-bit systems likewise use this technique to provide lock-free 128-bit types. – Nate Eldredge Jan 22 '22 at 04:55
  • So on x86-32, if FPU or SSE loads and stores weren't atomic, you'd still be able to use [`cmpxchg8b`](https://www.felixcloutier.com/x86/cmpxchg8b:cmpxchg16b) to get the same effect (more slowly). – Nate Eldredge Jan 22 '22 at 04:58

1 Answers1

0

This stack overflow answer shows how it's done an x86. Presumably other architectures have similar instructions.

How to guarantee 64-bit writes are atomic?

Frank Yellin
  • 9,127
  • 1
  • 12
  • 22