Guest User

Untitled

a guest
Jan 5th, 2016
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.23 KB | None | 0 0
  1. #define CAS(var, oldValue, newValue) __sync_bool_compare_and_swap(&(var), oldValue, newValue)
  2.  
  3. typedef struct ListItem;
  4. struct ListItem {
  5.     ListItem * volatile next;
  6.     bool locked;
  7.     bool removed;
  8. };
  9.  
  10. typedef struct List {
  11.     ListItem * volatile head;
  12.     ListItem * volatile current;
  13. } List;
  14.  
  15. List list;
  16.  
  17. void insertListItem(ListItem *item) {
  18.     if (!CAS(item->locked, false, true)) return;
  19.     if (item->removed == true) {
  20.         item->removed = false;
  21.         while (true) {
  22.             ListItem *head = list.head;
  23.             assert(item != head);
  24.             item->next = head;
  25.             if (CAS(list.head, item->next, item)) {
  26.                 break;
  27.             }
  28.         }
  29.     }
  30.     item->locked = false;
  31. }
  32.  
  33. void removeListItem(ListItem *item) {
  34.     if (!CAS(item->locked, false, true)) return;
  35.     if (item->removed == false) {
  36.         item->removed = true;
  37.         while (true) {
  38.             ListItem *prev = list.head;
  39.             if (prev == item) {
  40.                 ListItem *next = item->next;
  41.                 if (CAS(list.head, item, next)) {
  42.                     break;
  43.                 } else {
  44.                     continue;
  45.                 }
  46.             }
  47.             while (prev->next != item) {
  48.                 ListItem *next = prev->next;
  49.                 prev = next;
  50.             }
  51.             if (CAS(prev->next, item, item->next)) {
  52.                 ListItem *next = item->next;
  53.                 CAS(list.head, item, next);
  54.                 break;
  55.             }
  56.         }
  57.     }
  58.     item->locked = false;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment