I have a variable in shared memory x on a multi-processor system.
void MyFunction(volatile int* x) {
if (*x != 0) {
// do something
}
}
Other processes (possibly on different processors) will be writing to x using gcc built-in atomic operations such as __sync_bool_compare_and_swap etc.
I think I’m running into some cache concurrency issues where sometimes it takes a bit of time before x finally gets updated with the new value.
What I want is a kind of atomic_compare (without the swap), if such a thing exists? Or an “atomic read”. What’s the fastest way to do this? (avoiding mutexes, locks, etc.)
Thanks
Edit:
I just realized a somewhat hackish workaround would be to use __sync_val_compare_and_swap with a value that I knew it could never be. Would that solve the issue? (Is there a cleaner way?)
The new C standard, C11, has
_Atomicdata types and operations to deal with this. This standard is not yet implemented, but gcc and clang are close to it, they already implement the functionality. And in fact the function__sync_bool_compare_and_swapis part of it. I have wrapped that into a set of headers in P99 that let you program already with the C11 interfaces.The C11 function to do what you want would be
atomic_loador if you have particular requirements for the coherenceatomic_load_explicit. And no surprise, as you suspected, P99 maps that on__sync_val_compare_and_swap(&x, 0, 0). Then if you look into the assembler that this generates on most architectures this will just translate in a simple load operation in the case ofxbeeing anint. But this is not guaranteed by the language, it is up to the compiler to know such things and to synthesize the instructions that are guaranteed to be atomic.