Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fastest way to atomically compare two integers in C?

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?

like image 632
brooksbp Avatar asked Jun 26 '11 06:06

brooksbp


1 Answers

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.

like image 74
Eli Iser Avatar answered Oct 24 '22 16:10

Eli Iser