~/muadh/writing/spsc-fifo about writing

spsc lock-free, wait-free c++20 fifo

on a friday night after a practical midterm on c progamming, i watched a cppcon talk about a queue, past midnight, and then decided to build one. in my defence, the queue is very fast.

it is a queue with exactly two users: one puts things in, and one takes those things out. they're not allowed to share a lock, wait for each other, or even stand on the same cache line, and it moves 3.39 billion items a second...

my first numbers on windows were 18.7 million items a second, which felt a little off right up until i found out the operating system had been quietly shuffling my threads between cores the whole time, fixing that made it 5x faster and made me 5x happier with the results.

this writing is mostly for future me, who will have forgotten what acquire and release mean by next tuesday. if anything below is wrong, please tell me.

the Handle class being written in vim, with 22 errors showing in the status bar
the handle class, in vim, with 22 errors on the board. it compiles now, i promise.

a single-producer, single-consumer c++20 lock-free queue. it is bound to two cores on windows and has a throughput of 103 million items/s for single items and 3.39 billion for 256-item groups (1 batch needs only 1 signal).

the base code was developed from charles frasch's 2023 cppcon presentation, spsc lock-free, wait-free fifo from the ground up (code). improvements were made on top of his final version (fifo5):

threads in a pipeline can pass work to each other using an spsc queue. for example, one thread could receive network packets and another process them. this is intended to form the central part of a lock-free market data pipeline.

code files include: spsc.cpp (queue, self test and benchmarking); plot_results.py (graph); results_*.csv (benchmarking); throughput.png (graph output).

results

grouping items significantly improves throughput. as 1 notification is sent per group of 256 items, bulk mode has a throughput around 33x higher than single mode.

modenotifications sent per itemmedian (m items/s)min - max
bulk1 per 256 (or fewer)3,386.53,019.8 - 3,571.4
single1103.298.0 - 140.1
proxy1 per item (in place)86.585.4 - 87.1

system: amd ryzen 7 4700u (8 cores), windows 11, g++ 15.2.0 (msys2 ucrt64), -std=c++20 -O3 -march=native -DNDEBUG. consumer thread on cpu 0, producer on cpu 2. the fifo has 131,072 int64_t slots. 100 million items are processed per benchmark run. 10 runs per mode.

here are the same three launches as a graph, drawn by plot_results.py:

grouped bar chart of median throughput for single, proxy and bulk modes across three launches, on a log scale
all three launches land within a few percent of each other in every mode. the legend says cpu pairs, but every launch actually ran on cpus 0 and 2; my plotting script named them before it could read the setup header. error bars show min to max over 10 runs, on a log scale since bulk is around 33x single.
terminal output of the first benchmark run: single median 102.2, proxy 86.6, bulk 3,298.5 million items per second terminal output of the second benchmark run: single median 103.1, proxy 86.1, bulk 3,357.9 million items per second terminal output of the third benchmark run: single median 100.7, proxy 85.4, bulk 3,357.1 million items per second
three back-to-back launches, because one run is an anecdote. medians stayed within a few percent: single 100.7 to 103.1, proxy 85.4 to 86.6, bulk 3,298.5 to 3,357.9 m items/s. scroll sideways for all three.

the cpu model is now recorded automatically in the header of every benchmarking csv file (# cpu:).

key principles

correctness is assured by:

spsc, lock-free and wait-free

ring and cursors

data races

two threads simultaneously accessing the same plain memory, with at least one thread writing to it, and no ordering of these accesses. such behaviour is undefined. the presentation's fifo1 ran fine in a debug build, but crashed at -O2 with "invalid value". fifo1 suffered 4 data races:

  1. pushCursor_: producer writes, consumer reads.
  2. popCursor_: consumer writes, producer reads.
  3. slot: producer writes, consumer reads.
  4. slot one lap later: producer rewrites and the consumer may still be reading.

making cursors atomic resolves data races 1 and 2. ordering is required to resolve 3 and 4.

atomics

an atomic operation is indivisible. threads either observe it as not having begun or as having completed; they will not witness it mid-operation. again, this is not confined to one thread. it is precisely how threads safely share data.

as each cursor is written by only one thread, this queue does not require read-modify-write operations. plain atomic load and store functions suffice.

mutex

a mutex is used to protect a section of code (critical section). a thread calls lock(), executes the code and then calls unlock(). should another thread call lock() whilst this is occurring, it will wait. only threads accessing the same mutex are affected. modern c++ employs either std::lock_guard or std::scoped_lock to ensure that unlock() is not omitted.

mutexes are avoided in lock-free code. should a thread holding a mutex be put to sleep by the os, all waiting threads become blocked. moreover, threads can deadlock if they lock mutexes in reverse order. within the presentation, a mutex-based queue achieved a median throughput of 5.8m operations per second.

memory ordering

orderguaranteeapplied tox86 cost
seq_cst (default)all seq_cst operations follow one global order visible to all threadsnothing herestore becomes XCHG, a full fence
release (store)nothing that comes before can be reordered to come afterpublishing a cursorplain MOV
acquire (load)nothing that follows can be reordered to come beforereading another thread's cursorplain MOV
relaxedatomic, no orderinga thread reading its own cursorplain MOV

where an acquire load reads the value of a release store, the 2 threads synchronise: all actions carried out by the releasing thread prior to storing are visible to the acquiring thread from the point of loading.

false sharing and alignment

static_assert and lock-freedom

the c++ standard permits std::atomic to internally employ a lock where the cpu does not natively support the operation. static_assert(std::atomic<std::size_t>::is_always_lock_free) confirms at compile time that the cursors are genuinely cpu atomics. if not, compilation fails. there is no runtime overhead. by contrast, sanitizers are runtime tools which detect data races.

development

improvements within the presentation each enhanced throughput. commencing from fifo4a, the fastest version, this project incorporates further enhancements.

mutex queue not lock-free 5.8m fifo2 atomic cursors, seq_cst 12.6m fifo3 acquire/release + padding 41.9m fifo4 cached cursors 165.1m fifo5 zero-copy proxies, still % 162.8m fifo4a bit mask instead of % 690.7m, 4.2x fifo4 other spsc queues, same benchmark boost.lockfree fixed-size spsc_queue 101.9m rigtorp spscqueue cached cursors 330.7m
a bit mask instead of % took the talk's best queue from 165m to 691m ops/s. median millions of ops/s on an i7-9700, 131,072 slots of int64_t, from charles frasch's cppcon 2023 slides.
  1. fifo1: basic ring with % indexing. had 4 data races. ran fine in a debug build but produced an "invalid value" error at -O2.
  2. fifo2: atomic cursors with default seq_cst ordering. correct, but ++cursor involved a fenced read-modify-write. also, both cursors were on the same cache line.
  3. fifo3: release stores, and acquire loads for reading another thread's cursor. relaxed loads are used for reading one's own cursor. false sharing is addressed using alignas padding. throughput was around 3.3x that of fifo2.
  4. fifo4: cached copies of another thread's cursor. these are only updated when the queue appears to be full or empty, so, predominantly, the other core's cache line is never accessed.
  5. fifo4a: power-of-two sized fifo. cursor & mask_ supersedes cursor % capacity. this replaces a slow division operation with a 1-cycle and.
  6. fifo5: pusher and popper read and write slots in place. halving the number of memcpys is achieved in a read-socket, write-socket pipeline. fifo5 matches fifo4's throughput for an 8-byte int64_t.
  7. this project: combines fifo4a's mask and fifo5's handles. 128-byte padding is used. the ring is also aligned. try_emplace and bulk push/pop are included.

design and code

throughout, each thread only writes to its own memory. of all data, just the 2 cursors, each on its own cache line, cross cores.

fifo object, 640 bytes, on the stack +0 ring_, mask_ set once in the constructor; both only read +128 pushCursor_ (atomic) producer writes; consumer reads on refresh +256 cachedPopCursor_ producer only: its copy of popCursor_ +384 popCursor_ (atomic) consumer writes; producer reads on refresh +512 cachedPushCursor_ consumer only: its copy of pushCursor_ points to ring on the heap 131,072 slots of int64_t 1 mib, 128-byte aligned slot = cursor & mask_ key read across cores private to one thread read-only after construction
each thread writes only its own 128-byte lines; just the two cursors cross cores. memory layout of Fifo<int64_t>.

kCacheLine and alignment

kCacheLine is 128 bytes and is the alignas interval. being a compile-time constant, it does not execute. applying alignas(kCacheLine) to cursors ensures they begin on the next 128-byte boundary. padding bytes are inserted before them by the compiler. consequently, the blocks cannot share a line. similarly, alignas(kCacheLine) on the class ensures it too begins on a boundary. its size is then rounded up to 640 bytes, so neighbouring stack or heap data cannot share lines with it either. this supersedes the presentation's padding_ member.

ZeroCopyable

a c++20 concept which is true only if T is trivially copyable, trivially default-constructible and trivially destructible. push() and pop() depend on this. a pusher provides a pointer to a slot where no constructor was executed, and a popper frees a slot without executing a destructor. this is fine for int or a plain struct. yet for std::string, a garbage heap pointer would be read, so the compiler disallows it. nevertheless, try_push and try_pop continue to function for all T.

static_assert(is_always_lock_free)

should std::atomic internally use a lock (which would silently render the fifo non-lock-free), compilation fails.

slot() and mask

T* slot(std::size_t cursor) const noexcept {
    return ring_ + (cursor & mask_);
}
cursor (16 slots)binaryslotlap
0000000
151111150
161000001
3510001132

allocate()

bytes = (capa * sizeof(T) + kCacheLine - 1) / kCacheLine * kCacheLine;

rounding up the byte count to the nearest multiple of 128-byte blocks is achieved via this formula. rather than dividing by kCacheLine squared, it divides then multiplies, and integer division discards the remainder. moreover, adding 127 (rather than 128) preserves precise multiples (100 → 128; 128 → 128; 129 → 256 etc.). ::operator new(bytes, std::align_val_t{kAlign}) allocates raw, 128-byte-aligned memory. no objects are constructed. static_cast<T*> casts it. allocate is static so that it can be executed in the initialiser list of the constructor, before the object's members even exist.

free_slots() and ready_slots(): cached cursors

note: this is distinct from the false sharing remedy. whereas padding separates unrelated variables, cached cursors additionally prevent threads from reading each other's cache line for most operations.

constructor, copy and destructor

capa(), size(), empty(), full()

background housekeeping rather than fast operations. as size() first reads popCursor_, then pushCursor_, push - pop can never be negative, which would otherwise roll over to an extremely high unsigned integer. it is clamped to capa(), as push may advance between these 2 reads. all 3 values represent snapshots.

producer: try_emplace, try_push

  1. relaxed load of the producer's pushCursor_.
  2. if free_slots(pushCursor, 1) is 0, then return false (wait-free).
  3. std::construct_at creates the item in situ within the identified slot.
  4. pushCursor_.store(pushCursor + 1, release) publishes the cursor.

should construction throw, the cursor has not advanced and so the queue remains unmodified. both try_push(const T&) (copies) and try_push(T&&) (moves) utilise try_emplace.

consumer: try_pop

relaxed load of the consumer's popCursor_. if ready_slots is 0 then return false. transfer the item to out. std::destroy_at ends the item's lifetime (no action required for trivial types). popCursor_.store(popCursor + 1, release) frees the slot.

bulk: try_push_n, try_pop_n

items are transferred in up to 2 linear sections. this is because the ring is stored in memory as a flat array. again, a single release store is used to publish. continuing the earlier example of 16 slots and a push cursor located at slot 13, to push 6 items:

try_push_ntry_pop_n
items are copied into raw slots using std::uninitialized_copy_n.items are moved from slots into existing destination objects, using std::move.
no clean-up is required.std::destroy_n is used on slots that were read.
release store indicates that items are now available.release store indicates that slots are now freed.
a non-throwing copy constructor is required.non-throwing move assignment is required.

both functions return the number of items successfully transferred (potentially fewer than requested). [[nodiscard]] ensures that this value is not ignored. for int64_t, each section compiles down to one memmove.

handles: pusher and popper

template class Handle<bool IsPush> is utilised in 2 ways. whether it is a pusher or popper is determined at compile time:

calledreturnsIsPushdestructor advances
q.push() (producer)PushertruepushCursor_: item is ready
q.pop() (consumer)PopperfalsepopCursor_: slot is free
{
    auto p = q.push();      // reserve next slot
    if (p) {
        p->price = 100;     // write straight into the ring
        p->qty = 5;
    }
}                           // ~Handle: pushCursor_ + 1, consumer can now see it

benchmarking aids

benchmarking approach

in each benchmarking run, 100 million int64_t items (values 0, 1, 2 etc.) are pushed through the queue in 1 of 3 modes. the consumer thread verifies that each item is the expected next value. items per second are then calculated from the first push to the final pop.

modeproducer function(s)consumer function(s)notifications per item
singletry_push(i)try_pop(v)1 each
proxypush(), then *p = ipop(), then read *p1 each
bulktry_push_n(buf, 256)try_pop_n(buf, 256)1 per group each

logging results

a table is output to the screen. alongside this, the programme itself writes to results.csv. the csv begins with # lines detailing the system configuration. some of this information is automatically populated (cpu type using cpuid, compiler details from its version macros) and some must be manually inputted (kBuildFlags and kNotes):

# date: 2026-11-28 18:13:31
# cpu: <cpu model>
# os: Windows
# compiler: g++ 15.2.0
# flags: -std=c++20 -O3 -march=native -DNDEBUG
# pinned: consumer=cpu0 producer=cpu2
# capacity: 131072 slots, items/run: 100000000, batch: 256, runs: 10
# notes: plugged in, Best performance power mode
run,mode,ops_per_sec
1,single,98000000
1,proxy,85400000
1,bulk,3019800000

plotting

plot_results.py uses pandas to analyse the contents of each file named results_*.csv (ignoring the lines beginning with #). median and range statistics are produced for each mode and file. grouped bars on a log scale are then generated using matplotlib. information about the computer configuration (cpu, os, compiler, flags and run sizes) is shown under the graph. the graph is saved as throughput.png. a log scale is used since bulk throughput is around 33x that of single.

building and executing

fully optimise the build. execute in the folder where you wish results.csv to be saved. supply the consumer and producer core numbers and, optionally, the number of items.

windows (mingw g++ from msys2)

cd "C:\Users\Muadh Khan\Downloads\cpp_learn\spsc"
g++ -std=c++20 -O3 -march=native -DNDEBUG spsc.cpp -o spsc.exe
.\spsc.exe 0 2
.\spsc.exe 0 2 1000000   # fast test, 1m items per run

using msvc (developer powershell): cl /std:c++20 /O2 /EHsc /DNDEBUG spsc.cpp. always build in release mode and not debug mode.

linux and wsl2

g++ -std=c++20 -O3 -march=native -DNDEBUG -pthread spsc.cpp -o spsc
./spsc 0 2

race and memory detection (linux and wsl2 only)

g++ -std=c++20 -O1 -g -fsanitize=thread -pthread spsc.cpp -o spsc_tsan
./spsc_tsan 0 2 300000
g++ -std=c++20 -O1 -g -fsanitize=address,undefined -pthread spsc.cpp -o spsc_asan
./spsc_asan 0 2 2000000

sanitised builds are 20-50x slower, hence a small number of items is appropriate.

plotting

python -m pip install pandas matplotlib
python plot_results.py

ensure that the same version of python is used. should a (.venv) exist, install into that.

consistent figures

validation and issues

the queue successfully validates itself. threadsanitizer detects no races, and it immediately detects one when the memory ordering of a single store is relaxed.

validation

design validation

on a 2-core xeon cloud vm operating at 2.1 ghz, the best of 5 results (noting that results can be erratic, so only wide variations are significant):

alterationsingle mode (m items/s)analysis
cursor & mask_ (retained) v cursor % capacity~470 v ~250retain mask. approx 1.9x faster on this cpu.
128-byte v 64-byte paddingwithin errorretaining 128 bytes: suits intel and apple, for a few hundred extra bytes.
pause in spin loop v nonewithin errorretaining pause frees a hyper-threaded core-mate and reduces energy consumption.

windows issues

most of what i actually learned came from this table, mostly by getting things wrong first.

issueeffectrootresolution
lack of thread affinity setting on windowssingle mode: 18.7m items/s; proxy: 33.2m; bulk: 220.4mpin_to_cpu() contained only a linux conditional. on windows, it had no effect and the os relocated threads between cores.implemented SetThreadAffinityMask. medians increased to 103.2m, 86.5m and 3,386.5m respectively.
spsc::main lacked a return statementno csv file produced; segmentation fault on linux after the last line.it is undefined behaviour to exit a non-void function (apart from global main) without a return statement.append return 0;.
NOMINMAX redefinedcompiler warningmingw's standard library has already defined NOMINMAX.enclose it within #ifndef NOMINMAX.
no csv filefile not generated after buildthe csv is created when the programme runs, and saved to the current folder.execute the .exe in the desired folder.

constraints and future work

whilst the queue is fully realised for one producer and one consumer, most constraints relate to the validation process.

constraints

future work

glossary

termdefinition
acquireprevents subsequent loads and stores from moving before it. combined with a release store, it ensures that a thread's prior stores are visible to another thread.
alignas(N)ensures that a variable or class is located at an address divisible by n. padding is added before it.
atomictreated by other threads as indivisible.
cache linechunk of memory retained as a single entity in a cpu's cache. x86 cache lines are 64 bytes; apple m-series 128 bytes.
concepta c++20 compile-time predicate applied to a type (for instance, ZeroCopyable).
dereferenceaccess the value referenced by a pointer. for example, *p and p->field.
explicitprevents unspoken type conversion. Fifo<int> q = 1024; is invalid, and handles cannot covertly change into ints.
false sharingseparate variables updated by different threads reside on the same cache line, so the line is repeatedly transferred between cores.
hardware_destructive_interference_sizeminimum separation required between variables to prevent false sharing. for gcc and x86, this is 64 bytes.
memcpy and memmovefunctions for duplicating bytes. bulk addition/removal of trivial types compiles to these functions.
mutexmechanism permitting exclusive thread access to a section of code. threads attempting to lock it must wait.
relaxedan atomic operation without ordering guarantees. suitable for a thread accessing its own cursor.
releaseprecludes preceding loads and stores from moving after it. makes values stored by a thread available to another thread that acquire-loads the same variable.
release() (handle)prevents a pusher or popper from committing upon its destruction.
seq_cstdefault and most rigorous ordering. all seq_cst operations conform to one global sequence. on x86, this involves a complete fence for stores.
smart pointerobject that behaves as a pointer and handles resources upon going out of scope. the queue's handle facilitates slot commitment.
wait-freeall function calls complete in a finite number of steps irrespective of the other thread's activity.

references

thanks for reading this far. you now know more about cache lines than most people would ever want to. muadh