equality test for atomic variables in C and gcc
I have a dummy question about atomic variables using gcc.
My machine supports __sync_add_and_fetch
functio开发者_StackOverflown; I use this call in thread A to set my_variable (int)
.
I want Thread B reading that shared variable to test it against a value e.g. 20. Is it correct to write the following
if( __sync_bool_compare_and_swap( &my_variable, 20, 20 ) ){
//..Ok! It is 20 so go ahead!
}else{
// wrong: it is not ok.
}
If am not wrong in gcc the __sync_val_compare_and_swap
might fail when there is a race in the shared variable, but I don't know what it does return; how does it work with __sync_bool_compare_and_swap
?
Problem is what happens also when at the same time Thread A is changing the value using __sync_fetch_and_add
? Is it always guaranteed that it will return the value of that sum event when __sync_bool_compare_and_swap
is running concurrently?
Ideally speaking and for my purpose, I would really need a function doing exactly an atomic READ only, nor a Swap. Has C or gcc something like this?
Thanks A lot
AFG
As far as atomic operations go, they are meant to complete without interruption. If you have multiple atomic operations you expect to run concurrently, there will be a race condition concerning their order, but each will be run to completion. For example, say __sync_fetch_and_add
was first, it would perform both the fetch and the add before the __sync_bool_compare_and_swap
would perform its compare and swap.
You might also consider looking at other methods of signaling. You may have a race condition between the value being updated in one thread and having the other thread check it for the exact value 20. In other words, it could be updated right passed 20 with the other thread never knowing it.
But if none of this is too important, you could just do all this without any __sync*
functions since only one thread is writing and the other reading; no need to worry about corrupt data. Also no need to worry about the variable being up to date since you have a separate race condition involving that (value is updated faster than its checked).
Disclaimer: I haven't used the GCC _sync operations but I would imagine they are the same as the ones in MSVC. I do believe that should work. Atomic instructions are always executed as a single unit to prevent race conditions. Now, this assumes that the variable you are concerned about is not mapped to some physical hardware.
精彩评论