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.
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):
- power-of-two size, and a bitwise and in place of
%. - 128-byte padding for all hot variables, the fifo class and the ring, to ensure threads do not access the same cache line.
- grouped (bulk)
try_push_nandtry_pop_n. one notification is sent per group of items, rather than per item. try_emplaceconstructs items in situ. strong exception safety is provided and[[nodiscard]]ensures the return value of key functions is not ignored.- a benchmarking tool comprising bound threads, a spin-wait hint, 3 modes, a csv file of system information, and a python graph.
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.
| mode | notifications sent per item | median (m items/s) | min - max |
|---|---|---|---|
| bulk | 1 per 256 (or fewer) | 3,386.5 | 3,019.8 - 3,571.4 |
| single | 1 | 103.2 | 98.0 - 140.1 |
| proxy | 1 per item (in place) | 86.5 | 85.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:
- bulk throughput of 3.39 billion items/s represents around 27 gb/s of data transfer between 2 cores. as the consumer thread sequentially verifies all items, the throughput is genuine and not "skipped".
- single mode is not as good as in the presentation. fifo4a's masked version reached a median throughput of 691m items/s on an i7-9700. single mode is restricted by the rate at which a cache line can be transferred between the selected pair of cores. other core pairs could show greater throughput.
- proxy is marginally slower than single mode here. the proxy adds a pointer and a per-item check, and the compiler does not optimise these away. however, proxy's real advantage, avoiding copies of large structures, is not tested here as only an 8-byte
int64_tis used.
the cpu model is now recorded automatically in the header of every benchmarking csv file (# cpu:).
key principles
correctness is assured by:
- increasing counters;
- using atomics for counters;
- employing release and acquire to control ordering of slot data;
- and adding padding so that no 2 threads access the same cache line.
spsc, lock-free and wait-free
- spsc: one producer and one consumer thread.
- lock-free: no mutex. at all times, at least one thread is making progress, so a thread can never block another.
- wait-free: even more so. all function calls complete in a known maximum number of steps. on a full fifo,
try_pushimmediately returns false, rather than waiting.
ring and cursors
- the ring is a circular array of slots. following the last slot, indexing continues from slot 0.
pushCursor_andpopCursor_respectively count total items pushed and popped. neither is ever reset.- a cursor identifies a slot:
cursor & mask_. with 16 slots, cursor number 35 refers to slot 3 on lap 2. - items in the queue are given by
push - pop. a value of zero indicates an empty queue. capacity represents a full queue. furthermore, the producer is never more than 1 lap ahead of the consumer, since attempts to push to a full queue fail. - indefinite counting is key to distinguishing between empty and full queues. if both cursors are on the same slot, the difference is either zero or 16.
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:
pushCursor_: producer writes, consumer reads.popCursor_: consumer writes, producer reads.- slot: producer writes, consumer reads.
- 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.
- whilst a thread is executing an atomic operation, no other thread can access the relevant data. for example,
x.fetch_add(1)or++xis a read-modify-write operation. on x86 this translates into a locked instruction (such asLOCK XADD). no other core can therefore accessx. - however, a sequence of atomic operations is not indivisible. between
x.store(1)andx.store(2), another thread may both read and write its own value. - contention remains costly. many threads contending for one atomic cause its cache line to migrate between cores.
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
| order | guarantee | applied to | x86 cost |
|---|---|---|---|
seq_cst (default) | all seq_cst operations follow one global order visible to all threads | nothing here | store becomes XCHG, a full fence |
release (store) | nothing that comes before can be reordered to come after | publishing a cursor | plain MOV |
acquire (load) | nothing that follows can be reordered to come before | reading another thread's cursor | plain MOV |
relaxed | atomic, no ordering | a thread reading its own cursor | plain 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.
- race 3: write slot →
pushCursor_.store(release)⇒pushCursor_.load(acquire)→ read slot. - race 4: read slot →
popCursor_.store(release)⇒popCursor_.load(acquire)→ rewrite slot.
false sharing and alignment
- cache lines: cores cache memory in blocks (lines). on x86 these are 64 bytes in size. if any byte within a line is written to by a core, all other cores invalidate their copy of that line.
- false sharing: different threads write to separate variables, but these fall within the same line. consequently, each thread's write causes the other core to invalidate its copy of the line. even though threads never access the same variable, the line continues to shuttle back and forth between cores.
- correcting false sharing does not involve runtime re-alignment. instead,
alignasensures a variable begins at an address which is a multiple of n, and padding bytes are added before it by the compiler. different threads can then never write to the same line, and this stays fixed for the whole run. - why 128 bytes? intel's l2 prefetcher retrieves lines in 128-byte pairs, and on apple's m-series, lines are 128 bytes. by contrast, on x86,
std::hardware_destructive_interference_sizeevaluates to 64 bytes using gcc.
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.
- fifo1: basic ring with
%indexing. had 4 data races. ran fine in a debug build but produced an "invalid value" error at-O2. - fifo2: atomic cursors with default
seq_cstordering. correct, but++cursorinvolved a fenced read-modify-write. also, both cursors were on the same cache line. - 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
alignaspadding. throughput was around 3.3x that of fifo2. - 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.
- fifo4a: power-of-two sized fifo.
cursor & mask_supersedescursor % capacity. this replaces a slow division operation with a 1-cycle and. - 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. - this project: combines fifo4a's mask and fifo5's handles. 128-byte padding is used. the ring is also aligned.
try_emplaceand 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<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_);
}
mask_is equal tocapacity - 1. as capacity is a power of 2, its binary representation is all 1s (for 16 slots,0b1111).cursor & mask_retains the lower-order bits. this gives the same result ascursor % capacity, but without a division operation.ring_ + indexis pointer arithmetic. it gives the addressindexslots from the start.const: the queue is not modified.noexcept: no exceptions can be thrown, therefore no exception-handling code is generated for calls.
| cursor (16 slots) | binary | slot | lap |
|---|---|---|---|
| 0 | 0000 | 0 | 0 |
| 15 | 1111 | 15 | 0 |
| 16 | 10000 | 0 | 1 |
| 35 | 100011 | 3 | 2 |
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
free_slots()(producer): how many slots can i write to? it calculates available space fromcachedPopCursor_, which resides on the producer's own cache line. only if this suggests that there is insufficient space does it perform an acquire load of the actualpopCursor_(on the consumer's cache line). the cache is then updated and recalculation occurs.ready_slots()(consumer): how many items can i read? identical, but usingcachedPushCursor_andpushCursor_.- an out-of-date cache is always safe. as cursors are strictly increasing, an old value can never exceed the true value. thus, it can only underestimate, not overestimate, free or ready slots. consequently, the producer can never overwrite unread data.
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
explicit Fifo(capa)firstly rounds up capacity usingstd::bit_ceil(3 → 4, 1,000 → 1,024) and then allocates memory. theexplicitkeyword prevents implicit conversion such asFifo<int> q = 1024;.Fifo(Fifo const&) = deleteprevents copying. were 2 objects to share one ring, this would lead to double deallocation.~Fifo()is executed following both threads joining.if constexpr (!std::is_trivially_destructible_v<T>)ensures that only non-trivially destructible types have their destructors invoked. frompopCursor_topushCursor_, items are destroyed (relaxed loads are sufficient afterjoin()). finally, the ring is deallocated using the corresponding alignedoperator delete.
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
- relaxed load of the producer's
pushCursor_. - if
free_slots(pushCursor, 1)is 0, then return false (wait-free). std::construct_atcreates the item in situ within the identified slot.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:
first = min(6, 16 - 13) = 3- part 1: items 0, 1 and 2 are placed in slots 13, 14 and 15.
- part 2: items 3, 4 and 5 are stored in slots 0, 1 and 2.
pushCursor_is incremented by 6 in one store operation.
| try_push_n | try_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:
| called | returns | IsPush | destructor advances |
|---|---|---|---|
q.push() (producer) | Pusher | true | pushCursor_: item is ready |
q.pop() (consumer) | Popper | false | popCursor_: slot is free |
- members:
Fifo* fifo_(nullptrsignifies no slot, as either the fifo was empty/full,release()was executed, or the handle was moved from), andstd::size_t cursor_(identifying the slot). ~Handle()finalises processing. iffifo_is non-null,cursor_ + 1is stored (with release) in the cursor chosen byIsPush.explicit operator boolenablesif (auto p = q.pop()). theexplicitkeyword avoids situations such asint x = p;.release()aborts processing. for a pusher, the item is never published. for a popper, the item remains in the queue.get(),*and->provide in-situ access to a slot. for example:::read(sock, p.get(), sizeof(T));orp->price = 100;.- move only: the move constructor sets the source handle to null. this ensures that a slot is not finalised twice. declaring a move constructor also prohibits copying.
{
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
cpu_relax():_mm_pause()for x86,yieldfor arm64. included in spin-wait loops.pin_to_cpu(cpu): linux and windows affinity functions. has no effect elsewhere.require(ok, what): outputs and then terminates the programme; still operates with-DNDEBUG.self_test(): conducts the verification tests detailed below.ops_per_sec(...): starts the consumer thread on its core. main is pinned to the producer core. it then times the producer-to-join period and returns items per second.main: reads cores and item count. it then executesself_test(). the system information header is written. finally, the 3 modes are each benchmarked 10 times. a table is printed andresults.csvis generated.
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.
| mode | producer function(s) | consumer function(s) | notifications per item |
|---|---|---|---|
| single | try_push(i) | try_pop(v) | 1 each |
| proxy | push(), then *p = i | pop(), then read *p | 1 each |
| bulk | try_push_n(buf, 256) | try_pop_n(buf, 256) | 1 per group each |
- binding:
pin_to_cpu()is used to bind threads to specific cores (pthread_setaffinity_npfor linux,SetThreadAffinityMaskfor windows). without binding, the os reallocates threads between cores, and caches can then become cold. - physical cores: hyper-threaded siblings share an l1 cache and so do not represent a true core pair. examine the system layout using
lscpu -e(linux) or sysinternals coreinfo (windows). - spinning: should a thread determine that the queue is empty/full, it invokes
cpu_relax()(pause for x86, yield for arm) and re-attempts to process the queue. - timing:
std::chrono::steady_clockis used. it commences after the consumer thread has been started and ends following its joining. - multiple runs: there are 10 runs per launch. the median throughput is quoted along with a min-max range. an individual run is not representative. often, run 1 is slower as caches are being warmed up and the cpu boosts its clock speed.
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
- ensure that the laptop is plugged in and that windows is configured for best performance.
- close web browsers, games and chat programmes.
- test various core number combinations (such as
0 2,2 4etc.) and record the median of each. - optionally, a process can be started at high priority in command prompt by entering
start "" /b /wait /high spsc.exe 0 2.
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
- self-validation occurs before each benchmark. this includes: rounding up of capacity (for example, 3 becomes 4); adding items, refusing a 5th addition, sequential removal, and refusing a removal from an empty queue; 5 rounds of circular addition of heap-allocated
std::strings; a string left in the queue to validate destruction; pusher/popper commit, null handling andrelease(); bulk additions and removals that span the array boundary (including a partial addition to an almost full queue). - threadsanitizer: no races detected for any mode.
- addresssanitizer and undefinedbehaviorsanitizer: no memory leaks, out-of-bounds memory access or undefined behaviour.
- altering
pushCursor_.store(…)to use relaxed memory ordering causes threadsanitizer to detect a race intry_pop(). memory ordering is therefore integral to the operation.
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):
| alteration | single mode (m items/s) | analysis |
|---|---|---|
cursor & mask_ (retained) v cursor % capacity | ~470 v ~250 | retain mask. approx 1.9x faster on this cpu. |
| 128-byte v 64-byte padding | within error | retaining 128 bytes: suits intel and apple, for a few hundred extra bytes. |
| pause in spin loop v none | within error | retaining 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.
| issue | effect | root | resolution |
|---|---|---|---|
| lack of thread affinity setting on windows | single mode: 18.7m items/s; proxy: 33.2m; bulk: 220.4m | pin_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 statement | no 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 redefined | compiler warning | mingw's standard library has already defined NOMINMAX. | enclose it within #ifndef NOMINMAX. |
| no csv file | file not generated after build | the 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
- one active handle is permitted per side. were two pushers active simultaneously, they would access the same location. do not combine handles with
try_pushand/ortry_popwhere there is an active handle. size(),empty()andfull()provide instantaneous information which may quickly become outdated during programme execution.- capacity is rounded up to the nearest power of two. for example, 1000 locations results in 1024.
- bulk addition/removal requires types to be copyable and/or movable without exception (
is_nothrow_copy_constructibleand/oris_nothrow_move_assignable). proxy types must be trivially copyable. - although suitable for validation, the benchmark spins and so maintains 100% utilisation on 2 cores for the duration. a genuine pipeline might wish to reduce core utilisation further when idle.
- only throughput is analysed. there is currently no information regarding item transit time.
future work
- validate and graph several core number combinations.
- analyse latency, p50 and p99. apply
__rdtsc()to each item on addition, and on removal calculate the difference. ensure that the producer adds items at a constant rate so that the queue is not merely full, which avoids a situation where items are simply piling up. - integrate a mutex and condition variable queue, alongside the talk's fifo2-fifo4, into the same validation framework.
- incorporate a large structure (for example a 64-byte quote) to demonstrate proxy superiority over copying.
- contrast native windows, wsl2 and native linux.
- employ amd uprof or perf to analyse cache miss rates per item. this will substantiate padding and cached cursor efficacy.
glossary
| term | definition |
|---|---|
| acquire | prevents 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. |
| atomic | treated by other threads as indivisible. |
| cache line | chunk of memory retained as a single entity in a cpu's cache. x86 cache lines are 64 bytes; apple m-series 128 bytes. |
| concept | a c++20 compile-time predicate applied to a type (for instance, ZeroCopyable). |
| dereference | access the value referenced by a pointer. for example, *p and p->field. |
| explicit | prevents unspoken type conversion. Fifo<int> q = 1024; is invalid, and handles cannot covertly change into ints. |
| false sharing | separate variables updated by different threads reside on the same cache line, so the line is repeatedly transferred between cores. |
hardware_destructive_interference_size | minimum separation required between variables to prevent false sharing. for gcc and x86, this is 64 bytes. |
| memcpy and memmove | functions for duplicating bytes. bulk addition/removal of trivial types compiles to these functions. |
| mutex | mechanism permitting exclusive thread access to a section of code. threads attempting to lock it must wait. |
| relaxed | an atomic operation without ordering guarantees. suitable for a thread accessing its own cursor. |
| release | precludes 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_cst | default and most rigorous ordering. all seq_cst operations conform to one global sequence. on x86, this involves a complete fence for stores. |
| smart pointer | object that behaves as a pointer and handles resources upon going out of scope. the queue's handle facilitates slot commitment. |
| wait-free | all function calls complete in a finite number of steps irrespective of the other thread's activity. |
references
- charles frasch, spsc lock-free, wait-free fifo from the ground up (cppcon 2023). code. source of fifo1-fifo5 and comparative data.
- erik rigtorp, spscqueue: alternative cached cursor spsc queue.
- boost.lockfree, spsc_queue.
- amd uprof: windows and linux cpu profiler.
- further suggested viewing from the talk: fedor pikus, c++ atomics, from basic to advanced; timur doumler, what is low latency c++? (cppnow 2023, parts 1 and 2); robert leahy, taking a byte out of c++.
thanks for reading this far. you now know more about cache lines than most people would ever want to. muadh


