<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>C11 on Cheat Sheet</title><link>/tags/c11/</link><description>Recent content in C11 on Cheat Sheet</description><generator>Hugo</generator><language>en</language><atom:link href="/tags/c11/index.xml" rel="self" type="application/rss+xml"/><item><title>stdatomic</title><link>/programming/c/stdatomic/</link><pubDate>Mon, 01 Jan 0001 00:00:00 +0000</pubDate><guid>/programming/c/stdatomic/</guid><description>&lt;h1 id="stdatomic"&gt;&lt;code&gt;stdatomic&lt;/code&gt;&lt;a class="anchor" href="#stdatomic"&gt;#&lt;/a&gt;&lt;/h1&gt;
&lt;p&gt;The C11 standard (&lt;code&gt;&amp;lt;stdatomic.h&amp;gt;&lt;/code&gt;) provides hardware-level atomic memory operations and a formal memory model directly in the language without platform-specific inline assembly.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="1-why-atomic-operations-are-needed"&gt;1. Why Atomic Operations Are Needed&lt;a class="anchor" href="#1-why-atomic-operations-are-needed"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;Concurrent reads and writes to ordinary variables across multiple threads or &lt;code&gt;mmap&lt;/code&gt; shared-memory processes introduce two fundamental hazards:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Lost Update&lt;/strong&gt;: An increment such as &lt;code&gt;total += 100&lt;/code&gt; compiles into three separate machine steps: 1) memory &lt;code&gt;Load&lt;/code&gt;, 2) register &lt;code&gt;Add&lt;/code&gt;, and 3) memory &lt;code&gt;Store&lt;/code&gt;. If two threads read &lt;code&gt;1000&lt;/code&gt; at the same time, both store &lt;code&gt;1100&lt;/code&gt;, losing one increment.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Torn Read&lt;/strong&gt;: If one thread reads a 64-bit variable while another thread is halfway through updating it, the reader can observe a corrupted value combining the old upper 32 bits with the new lower 32 bits.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Atomic operations use CPU hardware instructions (eg. x86 &lt;code&gt;LOCK XADD&lt;/code&gt;, ARM &lt;code&gt;LDADD&lt;/code&gt;) to execute the access as a &lt;strong&gt;single indivisible step&lt;/strong&gt;, preventing both Lost Updates and Torn Reads.&lt;/p&gt;</description></item></channel></rss>