title: How Compare and Swap works
body: <p>I have read quite some posts that say compare and swap guarantees atomicity, However I am still not able to get how does it. Here is general pseudo code for compare and swap:</p>
  
  <pre><code>int CAS(int *ptr,int oldvalue,int newvalue)
  {
     int temp = *ptr;
     if(*ptr == oldvalue)
         *ptr = newvalue
     return temp;
  }
  </code></pre>
  
  <p>How does this guarantee atomicity? For example, if I am using this to implement a mutex, </p>
  
  <pre><code>void lock(int *mutex)
  {  
      while(!CAS(mutex, 0 , 1));
  }
  </code></pre>
  
  <p>how does this prevent 2 threads from acquiring the mutex at the same time? Any pointers would be really appreciated.</p>