I am writing a program in C. FOR SIMPLICITY LETS SAY: There are several variables that many threads can both read and write. Every time one of these is written it is written via an atomic swap (GCC atomic operations, sync and swap). Do I need to use an atomic load every time I read one of these variables, or are the atomic writes sufficient to avoid reading in data mid-write?
Note, anywhere that needs to use data from one of these vars first copies the value:
int success = 0;
while ( !success ) {
int x = shared_x;
... work with x, result in y ...
success = cmp_swap( &shared_x, x, y );
}
My question is not about a data race, that is I am not concerned I might loose data. MY concern is that the value of shared_x might change halfway through my reading it. Say it is an 8-byte integer, would this be a potential problem: say shared_x is a 64-bit integer, 8 bytes. Would it be possible that my x = shared_x will copy the first 4 bytes, then something atomically writes to shared_x, then this statement finishes reading the second 4 bytes. This would result in x containing the first 4 bytes of an old value of shared_x, and the last 4 bytes of the new shared_x. I suspect the memory barrier in the atomic swap (http://gcc.gnu.org/onlinedocs/gcc-4.1.1/gcc/Atomic-Builtins.html - using __sync_bool_compare_and_swap) is enough to protect against this... but I am not sure.