<?xml version="1.0" encoding="utf-8"?>
    <feed xmlns="http://www.w3.org/2005/Atom">
      <id>https://wolfgirl.dev/blog/</id>
      <title>PolyWolf's Blog - #c</title>
      <subtitle
        >all posts tagged "c" on a blog written by PolyWolf</subtitle
      >
      <icon>/apple-touch-icon.png</icon>
      <link href="/tags/c/rss.xml" rel="self" />
      <link href="https://wolfgirl.dev/blog/" />
      <updated>2024-03-10T14:15:22Z</updated>
      
    <entry>
      <title><![CDATA[wow another weekend project]]></title>
      <link rel="alternate" href="https://wolfgirl.dev/blog/4999112/" />
      <id>https://wolfgirl.dev/blog/4999112/</id>
      <published>2024-03-10T14:15:22Z</published>
      <updated>2024-03-10T14:15:22Z</updated>
      <summary><![CDATA[I show off a (probably very bad) lock-free header-only C library.]]></summary>
      <content type="html"><![CDATA[<p>Originally published on Cohost.</p><hr><p>Was talking with a friend, and he said something to the effect of "man, if only I had a lock-free ringbuffer right now..." I thought I had one of those lying around somewhere, but turns out I only sort of did:</p><ul><li>It was written in Rust, not C (hard to include in a random C project)</li><li>It only supported pushes and pops of single elements (inefficient)</li><li>It suffered from multiple logic bugs (atomic programming is hard!)</li></ul><p>So! To prove to myself that I can still write C code in a pinch, I decided to knock one out real fast. And I did! <a href=https://github.com/p0lyw0lf/silly_ringbuffer>https://github.com/p0lyw0lf/silly_ringbuffer</a> took a bit longer than expected (setting up C environment on Windows, solving some hard bugs like ABA), but overall I am very satisfied with the results.</p><h3 id=heading-included-features>Included Features<a aria-label="Link to heading 'Included Features'" data-heading-content="Included Features" class=anchor href=#included-features></a></h3><ul><li>Pushes and pops of arbitrary sizes (up to size of ringbuffer)</li><li>Threadsafe (safe to use without any external synchronization primitives)</li><li>Lock-free (only uses atomic variables internally)</li><li><del>Wait-free (threads always make progress if they can, and return an error if they can't)</del> maybe not?</li></ul><h3 id=heading-missing-features>Missing Features<a aria-label="Link to heading 'Missing Features'" data-heading-content="Missing Features" class=anchor href=#missing-features></a></h3><ul><li>No support for custom allocators (just uses <code>malloc</code> and <code>free</code>, tho this is the easiest to remedy)</li><li>No growable buffer (size must be known up-front)</li><li>No "pop everything remaining" operation</li><li>No synchronization-primitive-enabled variant (would be more efficient in cases of multiple readers or writers, currently there is just one part where we have to spin which is bad)</li></ul><p>I might add these features sometime much later, but for now I consider it "good enough"; I have proven the point to myself, and my friend can continue with his own silly C project (he wanted a lock-free ringbuffer because "sharing a file across a <code>fork()</code>" isn't cross-platform enough, doesn't work on Windows).</p><p>Also, despite being a hackathon-like project, I always write my code with lots of documentation, so <a href=https://github.com/p0lyw0lf/silly_ringbuffer/blob/6400f311e0eb9f26f5bd5ed89c00a62b096a98dc/srb.h#L86>go read it!!!</a> you might learn something <del>or find another bug idk</del></p>]]></content>
      <author>
        <name>PolyWolf</name>
        <uri>https://wolf.girl.technology/</uri>
      </author>
    </entry>
  
    <entry>
      <title><![CDATA[Learning Memory Order in C With Mutexes]]></title>
      <link rel="alternate" href="https://wolfgirl.dev/blog/2091838/" />
      <id>https://wolfgirl.dev/blog/2091838/</id>
      <published>2023-08-10T01:13:59Z</published>
      <updated>2023-08-10T01:13:59Z</updated>
      <summary><![CDATA[In which I (hopefully simply) explain C11's memory orderings using mutexes as a motivating example.]]></summary>
      <content type="html"><![CDATA[<p>Originally published on Cohost.</p><hr><p>oh wow i have been mega procrastinating on this. <a href=/blog/2064554/>read this first btw</a></p><h2 id=heading-lets-talk-about-volatile>Let's Talk About <code>volatile</code><a aria-label="Link to heading 'Let's Talk About volatile'" data-heading-content="Let's Talk About volatile" class=anchor href=#lets-talk-about-volatile></a></h2><p>So. <code>volatile</code>. The embedded programmer's best friend. But what does it actually mean?</p><p>From <a href=https://en.cppreference.com/w/c/language/volatile>cppreference</a>, emphasis mine:</p><blockquote><p>Every access (both read and write) made through an lvalue expression of volatile-qualified type is considered an observable side effect for the purpose of optimization and is evaluated strictly according to the rules of the abstract machine (that is, all writes are completed at some time before the next sequence point). This means that within <strong>a single thread of execution</strong>, a volatile access cannot be optimized out or reordered <strong>relative to another visible side effect</strong> that is separated by a sequence point from the volatile access.</p></blockquote><p>More simply, volatile reads and writes need to happen in the same order as you wrote them down in, but only with respect to "observable side effects" like syscalls or other volatile accesses.</p><p>So if you tried to use a standard <code>volatile int</code> for a mutex (ignoring the race condition and only focusing on a single thread):</p><pre class=syntax-highlighting><code class=language-c><span class=type>void</span> <span class=function>lock</span>(<span class=keyword>volatile</span> <span class=type>int</span><span class=operator>*</span> <span class=variable>m</span>) {
  <span class=type>int</span> <span class=variable>old_m</span> <span class=operator>=</span> <span class=number>1</span>;
  <span class=keyword>while</span> (<span class=variable>old_m</span>) {
    <span class=variable>old_m</span> <span class=operator>=</span> <span class=operator>*</span><span class=variable>m</span>;
    <span class=operator>*</span><span class=variable>m</span> <span class=operator>=</span> <span class=number>1</span>;
  }
}

<span class=type>void</span> <span class=function>unlock</span>(<span class=keyword>volatile</span> <span class=type>int</span><span class=operator>*</span> <span class=variable>m</span>) {
  <span class=operator>*</span><span class=variable>m</span> <span class=operator>=</span> <span class=number>0</span>;
}

<span class=type>void</span> <span class=function>do_stuff</span>(<span class=keyword>volatile</span> <span class=type>int</span><span class=operator>*</span> <span class=variable>m</span>, <span class=type>int</span><span class=operator>*</span> <span class=variable>shared</span>) {
  <span class=function>lock</span>(<span class=variable>m</span>);
  <span class=operator>*</span><span class=variable>shared</span> <span class=operator>=</span> <span class=number>5</span>;
  <span class=function>unlock</span>(<span class=variable>m</span>);
}</code></pre><p>Then, because the store to <code>shared</code> is non-volatile, it is not considered an observable side-effect, and can be freely reordered outside the critical section. You may then think "oh I'll just make everything inside the critical region volatile too!" but (1) this severely limits the optimizations compilers can do (those babies <em>love</em> to reorder stuff) and (2) that's not even the whole problem here. Remember, <code>volatile</code> only gives guarantees about single-threaded programs, and says nothing about multi-threaded ones.</p><details><summary>Note about the race condition:</summary> The swap of <code>old_m</code> and <code>*m</code> in the while loop isn't atomic, so an appropriate interleaving of two threads calling <code>lock()</code> could both enter the critical section, breaking mutual exclusion.</details><h2 id=heading-data-races>Data Races<a aria-label="Link to heading 'Data Races'" data-heading-content="Data Races" class=anchor href=#data-races></a></h2><p>What is a data race? Since we're using C, we can check <a href=https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2310.pdf>the C standard</a>, section 5.1.2.4. Paragraph 4 says (emphasis theirs):</p><blockquote><p>Two expression evaluations <em>conflict</em> if one of them modifies a memory location and the other one reads or modifies the same memory location.</p></blockquote><p>and Paragraph 35 says:</p><blockquote><p>The execution of a program contains a <em>data race</em> if it contains two conflicting actions in different threads, at least one of which is not atomic, and neither happens before the other. Any such data race results in undefined behavior.</p></blockquote><p>(where "before" is precisely defined in the other paragraphs).</p><p>With this in mind, let's take a look at my first attempt at the ticket lock implementation:</p><pre class=syntax-highlighting><code class=language-c><span class=keyword>#include</span> <span class=string>&lt;stdatomic.h></span>

<span class=keyword>typedef</span> <span class=keyword>struct</span> {
  <span class=type>atomic_int</span> <span class=property>next_ticket</span>;
  <span class=type>int</span> <span class=property>now_serving</span>;
} <span class=type>mutex_t</span>;

<span class=type>void</span> <span class=function>lock</span>(<span class=type>mutex_t</span> <span class=operator>*</span><span class=variable>m</span>) {
  <span class=type>int</span> <span class=variable>ticket</span> <span class=operator>=</span> <span class=function>atomic_fetch_add_explicit</span>(<span class=operator>&</span><span class=variable>m</span><span class=operator>-></span><span class=property>next_ticket</span>, <span class=number>1</span>, <span class=variable>memory_order_relaxed</span>);
  <span class=keyword>while</span> (<span class=variable>ticket</span> <span class=operator>!=</span> <span class=variable>m</span><span class=operator>-></span><span class=property>now_serving</span>) {}
}

<span class=type>void</span> <span class=function>unlock</span>(<span class=type>mutex_t</span> <span class=operator>*</span><span class=variable>m</span>) {
  <span class=operator>++</span><span class=variable>m</span><span class=operator>-></span><span class=property>now_serving</span>;
}</code></pre><p>Assume all uses of this API are correct (i.e. <code>lock()</code> always called before <code>unlock()</code>, no double-locking, and no double-unlocking within a thread). Can you spot the data race?</p><details><summary>(click for answer)</summary> That's right! <code>m->now_serving</code> is written to in <code>unlock()</code> and read from in <code>lock()</code> at the same time, and neither operation is atomic. If we assume that the compiler is not that smart and diligently translates our code into the assembly in the way we'd expect, then this works out fine: write before read means you see the write immediately, read before write is fine since we'll get it on the next iteration. But the compiler reasons that in the while loop, the value either <em>can</em> change (data race UB, since the loop is empty and there are no atomic updates in our program), or the value never changes (infinite loop UB. yes, certain non-terminating programs are UB) and can shoot our foot with whatever gun it likes.</details><p>Not to be deterred, I quickly fixed it:</p><pre class=syntax-highlighting><code class=language-c><span class=keyword>#include</span> <span class=string>&lt;stdatomic.h></span>

<span class=keyword>typedef</span> <span class=keyword>struct</span> {
  <span class=type>atomic_int</span> <span class=property>next_ticket</span>;
  <span class=type>atomic_int</span> <span class=property>now_serving</span>;
} <span class=type>mutex_t</span>;

<span class=type>void</span> <span class=function>lock</span>(<span class=type>mutex_t</span> <span class=operator>*</span><span class=variable>m</span>) {
  <span class=type>int</span> <span class=variable>ticket</span> <span class=operator>=</span> <span class=function>atomic_fetch_add_explicit</span>(<span class=operator>&</span><span class=variable>m</span><span class=operator>-></span><span class=property>next_ticket</span>, <span class=number>1</span>, <span class=variable>memory_order_relaxed</span>);
  <span class=keyword>while</span> (<span class=variable>ticket</span> <span class=operator>!=</span> <span class=variable>m</span><span class=operator>-></span><span class=property>now_serving</span>) {}
}

<span class=type>void</span> <span class=function>unlock</span>(<span class=type>mutex_t</span> <span class=operator>*</span><span class=variable>m</span>) {
  <span class=function>atomic_fetch_add_explicit</span>(<span class=operator>&</span><span class=variable>m</span><span class=operator>-></span><span class=property>now_serving</span>, <span class=number>1</span>, <span class=variable>memory_order_relaxed</span>);
}</code></pre><p>Great! Now that one of the updates is atomic, we've fixed the UB! That means we're done, right?</p><h2 id=heading-memory-ordering>Memory Ordering<a aria-label="Link to heading 'Memory Ordering'" data-heading-content="Memory Ordering" class=anchor href=#memory-ordering></a></h2><p>Not so fast! So far, we've just been setting the memory ordering parameter to the atomic operations to <code>memory_order_relaxed</code>, since that's the most flexible for the compiler<sup class=footnote-ref><a data-footnote-ref href=#fn-1 id=fnref-1>1</a></sup> and we only need atomic updates on individual variables to prevent data races.</p><p>However! Just like with <code>volatile</code>, C compilers are very aggressive about inlining functions and reordering load and stores, and since <code>memory_order_relaxed</code> doesn't impose any constraints on how the non-atomic loads and stores are sequenced, the compiler is still free to do whatever it wants. We're building a mutex after all, so it doesn't count if all we do is ensure the <code>lock()</code> and <code>unlock()</code> functions are race-free; we also need to make sure operations done in the critical section can't get reordered outside the <code>lock()</code> and <code>unlock()</code> calls.</p><p>Looking at the appropriate <a href=https://en.cppreference.com/w/c/atomic/memory_order>cppreference page</a> for other <code>memory_order</code> options, we see a couple that look interesting:</p><blockquote><p><code>memory_order_acquire</code>: A load operation with this memory order performs the acquire operation on the affected memory location: no reads or writes in the current thread can be reordered before this load. All writes in other threads that release the same atomic variable are visible in the current thread (see <a href=https://en.cppreference.com/w/c/atomic/memory_order#Release-Acquire_ordering>Release-Acquire</a> ordering)</p></blockquote><blockquote><p><code>memory_order_release</code>: A store operation with this memory order performs the release operation: no reads or writes in the current thread can be reordered after this store. All writes in the current thread are visible in other threads that acquire the same atomic variable (see <a href=https://en.cppreference.com/w/c/atomic/memory_order#Release-Acquire_ordering>Release-Acquire</a> ordering)</p></blockquote><p>Hey wait a minute, those names are familiar! "Acquire" is a fancy name for <code>lock()</code> and "release" is a fancy name for <code>unlock()</code>. These are memory orderings <em>specifically made for mutexes</em>; "reads or writes in the current threads" applies to <em>all</em> reads or writes, not just <code>volatile</code> ones. <code>memory_order_acquire</code> makes it so nothing in the critical section can be ordered before a <code>lock()</code>, and <code>memory_order_release</code> makes it so nothing in the critical section can be ordered after an <code>unlock()</code>. Perfect! With this in mind, we can write our final, correct<sup class=footnote-ref><a data-footnote-ref href=#fn-2 id=fnref-2>2</a></sup> ticket lock implementation:</p><pre class=syntax-highlighting><code class=language-c><span class=keyword>#include</span> <span class=string>&lt;stdatomic.h></span>

<span class=keyword>typedef</span> <span class=keyword>struct</span> {
  <span class=type>atomic_int</span> <span class=property>next_ticket</span>;
  <span class=type>atomic_int</span> <span class=property>now_serving</span>;
} <span class=type>mutex_t</span>;

<span class=type>void</span> <span class=function>lock</span>(<span class=type>mutex_t</span> <span class=operator>*</span><span class=variable>m</span>) {
  <span class=type>int</span> <span class=variable>ticket</span> <span class=operator>=</span> <span class=function>atomic_fetch_add_explicit</span>(<span class=operator>&</span><span class=variable>m</span><span class=operator>-></span><span class=property>next_ticket</span>, <span class=number>1</span>, <span class=variable>memory_order_relaxed</span>);
  <span class=keyword>while</span> (<span class=variable>ticket</span> <span class=operator>!=</span> <span class=variable>m</span><span class=operator>-></span><span class=property>now_serving</span>) {}
  <span class=function>atomic_thread_fence</span>(<span class=variable>memory_order_acquire</span>);
}

<span class=type>void</span> <span class=function>unlock</span>(<span class=type>mutex_t</span> <span class=operator>*</span><span class=variable>m</span>) {
  <span class=function>atomic_fetch_add_explicit</span>(<span class=operator>&</span><span class=variable>m</span><span class=operator>-></span><span class=property>now_serving</span>, <span class=number>1</span>, <span class=variable>memory_order_release</span>);
}</code></pre><p>Memory ordering is a super deep field, and I re-learn a lot of it every time I need to use it. Leaving u with one fun thing before I go, read about the <a href=https://www.cs.umd.edu/~pugh/java/memoryModel/AlphaReordering.html>DEC Alpha</a>. It's real cursed :3 <a href=https://en.wikipedia.org/wiki/Consistency_model#Relaxing_read_and_read_to_write_program_orders:_Alpha,_RMO,_and_PowerPC>Wikipedia has more</a> but that previous link is by far the simplest explainer of just how bonkers it is.</p><section class=footnotes data-footnotes><ol><li id=fn-1><p>In a bizarre twist of fate, the non-<code>_explicit</code> version of atomic functions all default to <code>memory_order_seqcst</code>, the most strict ordering. The C standard library having safe defaults?? Improbable. <a aria-label="Back to reference 1" class=footnote-backref data-footnote-backref data-footnote-backref-idx=1 href=#fnref-1>↩</a></p></li><li id=fn-2><p>Minus certain definitions of correct, such as actually descheduling blocked threads, detecting misuses of the API, detecting deadlocks, etc. <a aria-label="Back to reference 2" class=footnote-backref data-footnote-backref data-footnote-backref-idx=2 href=#fnref-2>↩</a></p></li></ol></section>]]></content>
      <author>
        <name>PolyWolf</name>
        <uri>https://wolf.girl.technology/</uri>
      </author>
    </entry>
  
    <entry>
      <title><![CDATA[Exploring Mutexes In C]]></title>
      <link rel="alternate" href="https://wolfgirl.dev/blog/2064554/" />
      <id>https://wolfgirl.dev/blog/2064554/</id>
      <published>2023-07-16T18:33:53Z</published>
      <updated>2023-07-16T18:33:53Z</updated>
      
      <content type="html"><![CDATA[<p>Originally published on Cohost under the title "yeah i got nerd-sniped" as a response to someone who posted under the "#c" tag with a simple spinlock implementation.</p><hr><p>i <em>love</em> talking about mutexes so now i'm going to make that everyone else's problem</p><p>ok so. indeed, that code is a relatively straightforward implementation of mutexes. i could digress into stuff about <code>volatile</code> and memory orderings, but instead, there is something more important we need to talk about before considering if this mutex is "good":</p><h2 id=heading-what-is-a-mutex>What Is A Mutex?<a aria-label="Link to heading 'What Is A Mutex?'" data-heading-content="What Is A Mutex?" class=anchor href=#what-is-a-mutex></a></h2><p>By its name, a mutex is something that provides <strong>Mut</strong>ual <strong>Ex</strong>clusion of a shared resource for concurrent tasks. In plain language:</p><blockquote><p>Only one task can access the thing at a time</p></blockquote><p>Programmers call it "acquiring" or "locking" the mutex when you attempt to access that shared resource, and "releasing" or "unlocking" the mutex when you had ownership of the resource and are giving it away for others to use.</p><p>Besides mutual exclusion, there's another property (not in the name) that's required for something to be a proper mutex:</p><h3 id=heading-progress>Progress<a aria-label="Link to heading 'Progress'" class=anchor data-heading-content=Progress href=#progress></a></h3><blockquote><p>No matter how many tasks are trying to acquire the mutex, if the resource isn't owned, someone will be able to get it</p></blockquote><p>It's hard to mess this one up; in fact I'd say most buggy mutex implementations skew the other way by not correctly providing mutual exclusion. To give a concrete example of how progress could be violated, consider the following implementation: (for some reason i couldn't put it inside a &lt;details>, sorry)</p><pre class=syntax-highlighting><code class=language-c><span class=keyword>#include</span> <span class=string>&lt;stdatomic.h></span>

<span class=keyword>typedef</span> <span class=keyword>struct</span> {
  <span class=type>queue_t</span> <span class=property>waiters</span>;
  <span class=type>atomic_int</span> <span class=property>owner</span>;
} <span class=type>mutex_t</span>;

<span class=keyword>static</span> <span class=keyword>const</span> <span class=type>int</span> <span class=constant>EMPTY</span> <span class=operator>=</span> <span class=number>0</span>;

<span class=type>void</span> <span class=function>lock</span>(<span class=type>mutex_t</span> <span class=operator>*</span><span class=variable>m</span>, <span class=type>int</span> <span class=variable>pid</span>) {
  <span class=keyword>if</span> (!<span class=function>atomic_compare_exchange_strong</span>(<span class=operator>&</span><span class=variable>m</span><span class=operator>-></span><span class=property>owner</span>, <span class=operator>&</span><span class=constant>EMPTY</span>, <span class=variable>pid</span>)) {
    <span class=function>push_back</span>(<span class=operator>&</span><span class=variable>m</span><span class=operator>-></span><span class=property>q</span>, <span class=variable>pid</span>);
    <span class=function>deschedule</span>(); <span class=comment>// Pauses execution until reschedule(pid) called</span>
  }
  <span class=variable>m</span><span class=operator>-></span><span class=property>owner</span> <span class=operator>=</span> <span class=variable>pid</span>;
}

<span class=type>void</span> <span class=function>unlock</span>(<span class=type>mutex_t</span> <span class=operator>*</span><span class=variable>mutex</span>) {
  <span class=type>int</span> <span class=variable>pid</span> <span class=operator>=</span> <span class=function>pop_front</span>(<span class=operator>&</span><span class=variable>m</span><span class=operator>-></span><span class=property>q</span>);
  <span class=keyword>if</span> (<span class=variable>pid</span> <span class=operator>!=</span> <span class=constant>EMPTY</span>) {
    <span class=function>reschedule</span>(<span class=variable>pid</span>);
  } <span class=keyword>else</span> {
    <span class=function>atomic_store</span>(<span class=operator>&</span><span class=variable>m</span><span class=operator>-></span><span class=property>owner</span>, <span class=constant>EMPTY</span>);
  }
}</code></pre><summary>Can you spot an error with this? I'll hide the intended solution in case you want to puzzle it out. <details><p>Between the <code>atomic_compare_exchange_strong</code> line and the <code>push_back</code> line, the current owner could release the mutex without noticing that we were trying to put ourselves on the queue. This violates progress because a single task trying to acquire the lock was not able to.</p> <p>There are certainly many other bugs, such as being able to race on <code>m->q</code> if it is not atomic. That is the thing about bugs, more pop up than u intend :)</details></summary><p>Progress and mutual exclusion are basically required for a correct mutex, but this last one is just nice to have:</p><h3 id=heading-bounded-waiting>Bounded Waiting<a aria-label="Link to heading 'Bounded Waiting'" data-heading-content="Bounded Waiting" class=anchor href=#bounded-waiting></a></h3><blockquote><p>If a task tries to acquire the mutex, it will eventually be the owner of the resource</p></blockquote><p>This can be strengthened further by putting bounds on how long it will take (a function of the number of competing tasks, proportional to), or weakened to deal with probabilistic algorithms. In any case, it's common for implementations attempting to go for bounded waiting do so at the cost of progress or mutual exclusion (by accident, as was the case in the example). So it is refreshing to see a simple spinlock that won't even try to deal with it.</p><p>However! Bounded waiting is still a very important property, and any non-specialized implementation should have it. Consider the following code:</p><pre class=syntax-highlighting><code class=language-c><span class=type>void</span> <span class=function>mainloop</span>(<span class=type>void</span>) {
  <span class=keyword>while</span> (!<span class=variable>should_stop</span>) {
    <span class=function>lock</span>(<span class=operator>&</span><span class=variable>m</span>);
    <span class=function>process</span>(<span class=operator>&</span><span class=variable>shared_resource</span>);
    <span class=function>unlock</span>(<span class=operator>&</span><span class=variable>m</span>);
  }
}</code></pre><p>To be clear, this is is a terrible, effectively single-threaded design. Still, it's not all that uncommon in real designs for threads to relatively quickly acquire and release the same mutex over and over, which can starve other threads if there isn't bounded waiting on the mutex.</p><h2 id=heading-can-we-achieve-bounded-waiting-with-only-stdatomich>Can We Achieve Bounded Waiting With Only <code>&lt;stdatomic.h></code>?<a aria-label="Link to heading 'Can We Achieve Bounded Waiting With Only <stdatomic.h>?'" data-heading-content="Can We Achieve Bounded Waiting With Only <stdatomic.h>?" class=anchor href=#can-we-achieve-bounded-waiting-with-only-stdatomich></a></h2><p>My claim is yes! Here is an example of such a mutex, known as a ticket lock:</p><pre class=syntax-highlighting><code class=language-c><span class=keyword>#include</span> <span class=string>&lt;stdatomic.h></span>

<span class=keyword>typedef</span> <span class=keyword>struct</span> {
  <span class=type>atomic_int</span> <span class=property>next_ticket</span>;
  <span class=type>atomic_int</span> <span class=property>now_serving</span>;
} <span class=type>mutex_t</span>;

<span class=type>void</span> <span class=function>lock</span>(<span class=type>mutex_t</span> <span class=operator>*</span><span class=variable>m</span>) {
  <span class=comment>// Get our ticket</span>
  <span class=type>int</span> <span class=variable>ticket</span> <span class=operator>=</span> <span class=function>atomic_fetch_add</span>(<span class=operator>&</span><span class=variable>m</span><span class=operator>-></span><span class=property>next_ticket</span>, <span class=number>1</span>, <span class=variable>memory_order_relaxed</span>);
  <span class=comment>// Spin until we are being served</span>
  <span class=keyword>while</span> (<span class=variable>ticket</span> <span class=operator>!=</span> <span class=variable>m</span><span class=operator>-></span><span class=property>now_serving</span>) {}
  <span class=function>atomic_thread_fence</span>(<span class=variable>memory_order_acquire</span>);
}

<span class=type>void</span> <span class=function>unlock</span>(<span class=type>mutex_t</span> <span class=operator>*</span><span class=variable>m</span>) {
  <span class=comment>// Let the next ticket be served</span>
  <span class=function>atomic_fetch_add</span>(<span class=operator>&</span><span class=variable>m</span><span class=operator>-></span><span class=property>now_serving</span>, <span class=number>1</span>, <span class=variable>memory_order_release</span>);
}</code></pre><p>How it works is fairly simple, and pretty much entirely explained in the comments already. It's inspired by how you'd wait in line at a deli or pharmacy.</p><p>Some great things about this lock:</p><ul><li>just one atomic operation to lock and unlock</li><li>small (8 bytes)</li></ul><p>Some not-great things about this lock:</p><ul><li>spin waiting :(</li><li>technically, <a href=https://en.wikipedia.org/wiki/ABA_problem>ABA</a>, but with 32-bit tickets this shouldn't be an issue in practice</li><li>doesn't detect misuse</li></ul><p>Most of these deficits could be solved by better design, but i am too lazy rn :P</p><p>Now, you may have still some questions like "wait why didn't you use <code>volatile</code>?" and "what's with that memory order stuff?", but this post is a little long as it stands, so I figure I'll leave the discussion about How Your Compiler And CPU Lie To You for a future post. Or just read <a href=https://faultlore.com/blah/tower-of-weakenings/>Tower Of Weakenings</a> because it answers or has links to answers for those questions and more.</p><p><del>And by the way, it's entirely possible I missed something and this code has a bug I am unaware of, so please do ask questions if you think something is up!</del><br><del>edit: I did get it wrong in multiple ways the first time. After talking with a few friends I am now more confident it is correct :) will explain in the later post</del><br>edit 2: I got it wrong again! Definitely making a post because explaining how I got things wrong is quite a journey.</p>]]></content>
      <author>
        <name>PolyWolf</name>
        <uri>https://wolf.girl.technology/</uri>
      </author>
    </entry>
  
    </feed>
  