multithreading - equality test for atomic variables in C and gcc -
i have dummy question atomic variables using gcc. machine supports __sync_add_and_fetch function; use call in thread set my_variable (int) .
i want thread b reading shared variable test against value e.g. 20. correct write following
if( __sync_bool_compare_and_swap( &my_variable, 20, 20 ) ){ //..ok! 20 go ahead! }else{ // wrong: not ok. } if not wrong in gcc __sync_val_compare_and_swap might fail when there race in shared variable, don't know return; how work __sync_bool_compare_and_swap?
problem happens when @ same time thread changing value using __sync_fetch_and_add? guaranteed return value of sum event when __sync_bool_compare_and_swap running concurrently?
ideally speaking , purpose, need function doing atomic read only, nor swap. has c or gcc this?
thanks lot
afg
as far atomic operations go, meant complete without interruption. if have multiple atomic operations expect run concurrently, there race condition concerning order, each run completion. example, __sync_fetch_and_add first, perform both fetch , add before __sync_bool_compare_and_swap perform compare , swap.
you might consider looking @ other methods of signaling. may have race condition between value being updated in 1 thread , having other thread check exact value 20. in other words, updated right passed 20 other thread never knowing it.
but if none of important, without __sync* functions since 1 thread writing , other reading; no need worry corrupt data. no need worry variable being date since have separate race condition involving (value updated faster checked).
Comments
Post a Comment