uint64_t n; // two 32-bit integers
return ( (uint32_t)(n >> 32) == (uint32_t)n );
What is the fastest way to atomically compare the 32 most-significant bits to the 32 least-significant bits of a uint64_t?
I think one horrible solution is to do: acquire spinlock, read 32 LSB, read 32 MSB, compare to get result, release spinlock, return result. Is there any way to do this without having to take a spinlock?
How about using a compare-exchange operation on the two different addresses?
Something like: CMPXCHG (int*)&n, (((int*)&n)+1)
(note - this actually cannot work).
Edit: changed the syntax to more closely resemble the actual x86 syntax.
Edit 2: as Serge has pointed out, using two memory addresses in an assembly instruction is not supported for most assemblies, so this way can't work directly from memory. This means that this approach can't be used for comparing the two 32 bits portions of a 64 bit variable in an atomic fashion.
Some assemblies (PowerPC at least) are able to provide special instructions (for PowerPC, LWARX and STWCX) that can make this work in a multi-threaded safe way, but it is not exactly what the OP asked, nor will it work for x86.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With