   1.   #include <stdio.h>  
   2.  #include <stdlib.h>  
   3. //exchange - newvalue, comperand is old/expected value  
   4. /* 
   5.  * Function actually does the following thing - if the value at *dest is equal to oldvalue then replace it by newvalue else 
leave it unchanged : do all these atomically 
   6.  * 
   7.  * There are two options for return value 
   8.  *  1.is initial value of *dest and leave the burden of calling fxn to compare it with oldval 
   9.  *  2. do it over here and return 0 or 1, this should be more efficient 
  10.  * */  
  11.   
  12. /* later change it into macro  */  
  13. int cas(int* dest, int oldvalue, int newvalue){  
  14.     printf("(%d,%d,%d)",*dest,oldvalue,newvalue);  
  15.     /* int cas(int dest, int oldvalue, int newvalue){ */  
  16.     /* int cas(int dest, int newvalue, int oldvalue){ */  
  17.     int result= 1;/* 1 shows that cas succeeded and 0 shows that it failed  */  
  18.     /* btw need to set cc for flag clobbering !  */  
  19.     __asm__ __volatile__(  
  20.             "movl %2, %%eax\n\t"  
  21.             "movl %3, %%ebx\n\t"  
  22.             "movl %0, %%ecx\n\t"  
  23.             "LOCK\n\t"  
  24.             "CMPXCHG %%ebx, (%%ecx)\n\t"  /* should LOCK be on the same line  */  
  25.             "jz DONE\n\t"  
  26.             "movl $0, %1\n\t "  
  27.             "DONE: \n\t"  
  28.             :"=m"(dest),"=g"(result)  
  29.             :"g" (oldvalue),"g" (newvalue),"m"(dest)  
  30.             :"%eax","%ebx","ecx","cc"  
  31.             );  
  32.     printf("(%d,%d,%d)",*dest,oldvalue,newvalue);  
  33.     return result;  
  34. }  
  35.   
  36. /* TODO 
  37.  * write another asm fxn which puts above fxn in a while loop and keep trying unless it succeeds*/  
  38.   
  39. int main(){  
  40.     int a= 5,b= 6;  
  41.     int* c = (int*) malloc(sizeof(int));  
  42.     *c= 6;  
  43.     /* int c= 6; */  
  44.     printf("%d\n",cas(c,b,b));  
  45.     printf("%d\n",cas(c,b,a));  
  46.     printf("%d\n",cas(c,a,a));  
  47.     printf("%d\n",cas(c,b,b));  
  48.     *c= 6;  
  49.     /* c= 5; */  
  50.     printf("changing value of *c to %d\n",*c);  
  51.     printf("%d\n",cas(c,b,b));  
  52.     printf("%d\n",cas(c,b,a));  
  53.     printf("%d\n",cas(c,a,a));  
  54.     printf("%d\n",cas(c,a,b));  
  55.     printf("%d\n",cas(c,b,a));  
  56.     return 0;  
  57. }  
  58. </stdlib.h></stdio.h>  
