ulvis.paste.net - pastebin

Paste Search Dynamic
Recent pastes
compare and swap
  1. #include <stdio.h>
  2.  
  3. int global = 0;
  4.  
  5. char compare_and_swap(int* ptr, int old, int new) {
  6.         unsigned char ret;
  7.         // Note that sete sets a ’byte’ not the word
  8.         __asm volatile(
  9.                 " lock\n"
  10.                 " cmpxchgl %2,%1\n"
  11.                 " sete %0\n"
  12.                 : "=q" (ret), "=m" (*ptr)
  13.                 : "r" (new), "m" (*ptr), "a" (old)
  14.                 : "memory");
  15.         return ret;
  16.  
  17.  
  18. }
  19.  
  20. int main(int argc, char* argv[]) {
  21.         printf("before successful cas: %d\n", global);
  22.         int success = compare_and_swap(&global, 0, 100);
  23.         printf("after successful cas: %d (success: %d)\n", global, success);
  24.  
  25.         printf("before failing cas: %d\n", global);
  26.         success = compare_and_swap(&global, 0, 200);
  27.         printf("after failing cas: %d (old: %d)\n", global, success);
  28.  
  29.         return 0;
  30. }
  31.  
Parsed in 0.005 seconds