Atomic exchange with CAS (using the built-in gcc built-in synchronizers)

Can I use the compare and replace function to automatically switch variables? I use C / C ++ through gcc on x86_64 RedHat Linux, specifically the built-in __sync. Example:

   int x = 0, y = 1; 
   y = __sync_val_compare_and_swap(&x, x, y);

I think it comes down to whether x can change between & x and x; for example, if & x is an operation, it may be possible for x to change between & x and x in the arguments. I want to assume that the above comparison will always be true; my question is: can I. Obviously, there is a bool version for CAS, but then I cannot get old x to write to y.

A more useful example would be to insert or remove a linked list from the header (gcc claims to support pointer types, so suppose they have an element and a head):

   elem->next = __sync_val_compare_and_swap(&head, head, elem); //always inserts?
   elem = __sync_val_compare_and_swap(&head, head, elem->next); //always removes?

Link: http://gcc.gnu.org/onlinedocs/gcc/Atomic-Builtins.html

+5
source share
3 answers

- , , . CAS , - , . , , , - , , , .

, :

elem->next = __sync_val_compare_and_swap(&head, head, elem); //always inserts?

. , , __sync_val_compare_and_swap(), head ( , , ),

- head , , head , next , . , , .

, - :

whatever_t* prev_head = NULL;
do {
    elem->next = head;  // set up `elem->head` so the list will still be linked 
                        // correctly the instant the element is inserted
    prev_head = __sync_val_compare_and_swap(&head, elem->next, elem);
} while (prev_head != elem->next);

bool, :

do {
    elem->next = head;  // set up `elem->head` so the list will still be linked 
                        // correctly the instant the element is inserted
} while (!__sync_bool_compare_and_swap(&head, elem->next, elem));

, , ( ). insert_element() ( , ).

ABA:

, ABA " ". , X , elem->next = head, head A1.

__sync_val_compare_and_swap() :

  • A1 , head B
  • - A1
  • , A2, , , , A1
  • A2 , head A2

A1 A2 /, ABA.

, X , head , - , , , X :

  • ,
  • ,
  • , X ( )
+3

. CAS x86 / .

, .

x &x x? , , .

& .

, Foo(x, x), x, :

  • x
  • x

, x.

0

, , - . .

However, you still have a problem with the race conditions between assignments y. Sometimes it yis local, and in this case it will be safe, but if both xand yare common, you have a big problem and the need for its elimination lock.

0
source

All Articles