From 12M ops/s to 305 M ops/s on a lock-free ring buffer.<p>In this post, I walk you step by step through implementing a single-producer single-consumer queue from scratch.<p>This pattern is widely used to share data between threads in the lowest-latency environments.
Something to add to this; if you're focussing on these low-level optimizations, make sure the device this code runs on is actually tuned.<p>A lot of people focus on the code and then assume the device in question is only there to run it. There's so much you can tweak. I don't always measure it, but last time I saw at least a 20% improvement in Network throughput just by tweaking a few things on the machine.
Random idea: If you have a known sentinel value for empty could you avoid the reader needing to read the writer's index? Just try to read, if it is empty the queue is empty, otherwise take the item and put an empty value there. Similarly for writing you can check the value, if it isn't empty the queue is full.<p>It seems that in this case as you get contention the faster end will slow down (as it is consuming what the other end just read) and this will naturally create a small buffer and run at good speeds.<p>The hard part is probably that sentinel and ensuring that it can be set/cleared atomically. On Rust you can do `Option<T>` to get a sentinel for any type (and it very often doesn't take any space) but I don't think there is an API to atomically set/clear that flag. (Technically I think this is always possible because the sentinel that Option picks will always be small even if the T is very large, but I don't think there is an API for this.)
Yeah, or you could put a generation number in each slot adjacent to T and a read will only be valid if the slot's generation number == the last one observed + 1, for example. But ultimately the reader and writer still need to coordinate here, so we're just shifting the coordination cache line from the writer's index to the slot.
Great article, thanks for sharing. And such a lovely website too :)
Great post!<p>Would you mind expanding on the correctness guarantees enforced by the atomic semantics used? Are they ensuring two threads can't push to the same slot nor pop the same value from the ring? These type of atomic coordination usually comes from CAS or atomic increment calls, which I'm not seeing, thus I'm interested in hearing your take on it.
I see you replied on comment below with:<p>> note that there are only one consumer and one producer<p>That clarify things as you don't need multi-thread coordination on reads or writes if assuming single producer and single consumer.
Thanks! That's not ensured, optimizations are only valid due to the constraints<p>- One single producer thread<p>- One single consumer thread<p>- Fixed buffer capacity<p>So to answer<p>> Are they ensuring two threads can't push to the same slot nor pop the same value from the ring?<p>No need for this usecase :)
This is a SPSC queue -- there aren't multiple writers to coordinate, nor readers. It simplifies the design.
I had what I thought was a pretty good implementation, but I wasn't aware of the cache line bouncing. Looks like I've got some updates to make.
Super fun, def gonna try this on my own time later
This is in C++, other languages have different atomic primitives.
Don't most people use C++11 atomics now? You have SeqCst, Release, Acquire, and Relaxed (with Consume deprecated due to the difficulty of implementing it). You can do loads, stores, and exchanges with each ordering type. Zig, Rust, and C all use the same orderings. I guess Java has its own memory model since it's been around a lot longer, but most people have standardized around C++'s design.<p>Which is a slight shame since Load-Linked/Store-Conditional is pretty cool, but I guess that's limited to ARM anyways, and now they've added extensions for CAS due to speed.
I've taken an interest in lock-free queues for ultra-low power embedded... think Cortex-m0, or even avr/pic.<p>Things get interesting when you're working with a cpu that lacks the ldrex/strem assembly instructions that makes this all work. I think youre only options at that point are disable/enable interrupts. IF anyone has any insights into this constraint I'd love to hear it.
LL/SC is still hinted at in the C++11 model with std::atomic<T>::compare_exchange_weak:<p><a href="https://en.cppreference.com/w/cpp/atomic/atomic/compare_exchange.html" rel="nofollow">https://en.cppreference.com/w/cpp/atomic/atomic/compare_exch...</a>
JVM has almost the same (C++ memory model was modeled after JVM one, with some subtle fixes).
Really? Pretty much all atomics i’ve used have load,
store of various integer sizes. I wrote a ring buffer in Go that’s very similar to the final design here using similar atomics.<p><a href="https://pkg.go.dev/sync/atomic#Int64" rel="nofollow">https://pkg.go.dev/sync/atomic#Int64</a>
Nice one, thanks for sharing. Do you wanna share the ring buffer code itself?
They generally map directly to concepts in the CPU architecture. On many architectures, load/store instructions are already guaranteed to be atomic as long as the address is properly aligned, so atomic load/store is just a load/store. Non-relaxed ordering may emit a variant load/store instruction or a separate barrier instruction. Compare-exchange will usually emit a compare and swap, or load-linked/store-conditional sequence. Things like atomic add/subtract often map to single instructions, or might be implemented as a compare-exchange in a loop.<p>The exact syntax and naming will of course differ, but any language that exposes low-level atomics at all is going to provide a pretty similar set of operations.
Yeah, this is quite specific to C++ (at a syntax level)
Huh? Other languages that compile to machine code and offer control over struct layout and access to the machine’s atomic will work the same way.<p>Sure, C++ has a particular way of describing atomics in a cross-platform way, but the actual hardware operations are not specific to the language.
[dead]
[flagged]
[flagged]
It's obviously, trivially broken. Stores the index before storing the value, so the other thread reads nonsense whenever the race goes against it.<p>Also doesn't have fences on the store, has extra branches that shouldn't be there, and is written in really stylistically weird c++.<p>Maybe an llm that likes a different language more, copying a broken implementation off github? Mostly commenting because the initial replies are "best" and "lol", though I sympathise with one of those.
> It's obviously, trivially broken. Stores the index before storing the value, so the other thread reads nonsense whenever the race goes against it.<p>Are we reading the same code? The stores are clearly <i>after</i> value accesses.<p>> Also doesn't have fences on the store<p>?? It uses acquire/release semantics seemingly correctly. Explicit fences are not required.
Push:<p>buffer_[head] = value;<p>head_.store(next_head, std::memory_order_release);<p>return true;<p>There's no relationship between the two written variables. Stores to the two are independent and can be reordered. The aq/rel applies to the index, not to the unrelated non-atomic buffer located near the index.
This is just wrong. See <a href="https://en.cppreference.com/w/cpp/atomic/memory_order.html" rel="nofollow">https://en.cppreference.com/w/cpp/atomic/memory_order.html</a>. Emphasis mine:<p>> A store operation with this memory order performs the release operation: <i>no reads or writes in the current thread</i> can be reordered after this store. <i>All writes in the current thread</i> are visible in other threads that acquire the same atomic variable (see Release-Acquire ordering below) and writes that carry a dependency into the atomic variable become visible in other threads that consume the same atomic (see Release-Consume ordering below).
> There's no relationship between the two written variables. Stores to the two are independent and can be reordered. The aq/rel applies to the index, not to the unrelated non-atomic buffer located near the index.<p>No, this is incorrect. If you think there's no relationship, you don't understand "release" semantics.<p><a href="https://en.cppreference.com/w/cpp/atomic/memory_order.html" rel="nofollow">https://en.cppreference.com/w/cpp/atomic/memory_order.html</a><p>> 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.
write with release semantic cannot be reordered with any other writes, dependent or not.<p>Relaxed atomic writes can be reordered in any way.
> write with release semantic cannot be reordered with any other writes, dependent or not.<p>To quibble a little bit: <i>later</i> program-order writes CAN be reordered <i>before</i> release writes. But <i>earlier</i> program-order writes may not be reordered <i>after</i> release writes.<p>> Relaxed atomic writes can be reordered in any way.<p>To quibble a little bit: they can't be reordered with other operations on the same variable.
Yep, you are right, more precise, and precision is very important in this topic.<p>I stand corrected.
Sorry, but that's not actually true. There are no data races, the atomics prevent that (note that there are only one consumer and one producer)<p>Regarding the style, it follows the "almost always auto" idea from Herb Sutter