Lock-free multithreading with atomic operations
Yet another article discussing atomics without discussing the memory model or memory fences.<p>Atomics are the easy part to understand. Memory fences and memory-ordering is the hard part that needs far more discussion. If you use atomics with the wrong memory fence, everything will break.<p>Memory fences are necessary to make the compiler, CPU, and caches put the data into main-memory in the correct order.<p>----------<p>Do NOT write Atomics unless you understand fences. It is absolutely essential, even on x86, to put memory fences in the correct spot. Even though x86 automatically has acquire&#x2F;release consistency... the compiler may move your data ordering to the wrong location. Even with &quot;volatile&quot; semantics, your data may be committed to memory in the wrong order.<p>Fredor Pikus has an amusing example where you can have a properly coded lock but the compiler (may) mess you up: <a href="https:&#x2F;&#x2F;youtu.be&#x2F;lVBvHbJsg5Y?t=811" rel="nofollow">https:&#x2F;&#x2F;youtu.be&#x2F;lVBvHbJsg5Y?t=811</a><p>----------<p>EDIT: if you use locks (spinlocks, mutex, condition variables, etc. etc.), the author of the library would have put memory fences in the correct place for you. Only if you use synchronization &quot;manually&quot; (and... you probably are doing that if you are writing atomics), do you have to think about memory fences.