title: How does a compare and swap loop achieve atomicity?
body: <p>This page talks about a CAS loop in details: <a href="https://preshing.com/20150402/you-can-do-any-kind-of-atomic-read-modify-write-operation/" rel="nofollow noreferrer">https://preshing.com/20150402/you-can-do-any-kind-of-atomic-read-modify-write-operation/</a></p>
  <p>An example of <code>fetch_multiply</code> in C++:</p>
  <pre class="lang-cpp prettyprint-override"><code>uint32_t fetch_multiply(std::atomic&lt;uint32_t&gt;&amp; shared, uint32_t multiplier){
      uint32_t oldValue = shared.load();
      while (!shared.compare_exchange_weak(oldValue, oldValue * multiplier)){}
      return oldValue;
  }
  </code></pre>
  <p>Essentially if the <code>*memory</code> value matches our oldValue then a <code>newValue</code> gets stored atomically, else oldValue get updated with <code>*memory</code>.</p>
  <p>I have 2 questions:</p>
  <p>1 - Why do we have to check if <code>oldValue</code> is still unchanged in memory? What happens if we just write newValue to memory? Are we trying to avoid overwriting or using an intermediate value from another thread?</p>
  <p>2- Suppose this scenario with 2 threads:</p>
  <ul>
  <li>Thread B is trying to store a non-aligned value non-atomically. Store tearing occurs.</li>
  <li>Thread A attempts a swap.</li>
  <li>Swap fails as oldValue doesn't match. An <strong>intermediate</strong> (teared) value from memory gets loaded to our oldValue.</li>
  <li>Thread A does multiplication with an <strong>intermediate</strong> value and attempts another swap which succeeds.</li>
  <li>Now Thread B writes the remaining of its values to the same location partially overwriting our previous write.</li>
  </ul>
  <p>I'm assuming <code>Thread B</code> could operate with that much delay and if so not only we
  multiplied with an intermediate value, it even got partially overwritten afterwords and CAS did nothing.</p>