Search code examples
c++winapix86multicoreatomic

How to perform atomic 64b read on x86 (Pentium and above)?


I would like to perform and atomic read of 64b aligned 64b data on x86 platform (Pentium or above guaranteed).

Is there a way to do this? (And no, I do not want to use a critical section or a mutex for this, I want this to be lock-free).


Solution

  • Use the Interlocked operations, here's some sample code:

    LONGLONG AtomicRead(LONGLONG* p)
    {
        return InterlockedCompareExchange64(p, 0, 0);
    }
    

    This does the compare exchange against zero and sets p to zero if it's already equal to zero -ie, it's a noop. InterlockedCompareExchange returns the original 64 bit value pointed to by p.