I'm doing inter-process communication using shared memory on a multi-processor server. I've simplified the code to the following:
struct MyStruct {
uint64_t x;
};
volatile MyStruct* my_struct; // initialized elsewhere
void MyFunction(uint64_t y) {
while (true) {
uint64_t current_x = my_struct->x;
if (__sync_bool_compare_and_swap(&my_struct->x, current_x, y)) {
DoWork(current_x, y); // do work here depending on current_x and y
return;
}
}
}
My question: is this code correct?
In particular, do I need to add a
__sync_synchronize()
before the line
uint64_t current_x = my_struct->x
or will that be redundant since the atomic CAS on the following line effectively does that anyways? As you can see, what effectively I want is the __sync_lock_test_and_set functionality. However, from http://gcc.gnu.org/onlinedocs/gcc-4.1.1/gcc/Atomic-Builtins.html it looks like that function may not work always as expected.