TExcelTAD
Home › Game Engine Architecture in C++ › Lock-Free Queues and False Sharing

Lock-Free Queues and False Sharing

A mutex is the right default for shared data: simple, correct, and cheap when nobody else holds it. Two situations push engines past it. First, a few hot paths (the job queue itself, the audio thread's command queue, the logger) are hit thousands of times per frame from several threads, and contention on one lock shows up in the profiler. Second, some threads must never block: the audio callback has a few milliseconds to fill its buffer, and waiting on a lock held by a thread the OS just paused means an audible glitch.

Lock-free data structures use atomic operations instead of locks, so no thread can stop the others from making progress. This lesson covers the concepts, the one lock-free structure every engine has (a single-producer single-consumer ring buffer) and a performance trap that has nothing to do with locks: false sharing.

Atomics and memory order in one table

Operation What it guarantees
std::atomic<T>::load/store no torn reads/writes; other threads see a whole value
fetch_add, exchange read-modify-write as one indivisible step
compare_exchange_weak/strong "if it's still X, set it to Y", the building block of lock-free algorithms
memory_order_release on a store everything this thread wrote before the store is visible to a thread that...
memory_order_acquire on a load ...reads that value with acquire, after its load
memory_order_relaxed atomicity only, no ordering of other memory; fine for statistics counters
memory_order_seq_cst (default) acquire + release + a single global order; safest, sometimes slower

Release/acquire is the pattern to remember: the producer writes the data, then releases an index; the consumer acquires the index, then reads the data and is guaranteed to see it.

A single-producer single-consumer ring buffer

With exactly one writer and one reader, a ring buffer needs no compare-exchange at all. The producer owns head, the consumer owns tail, and each only reads the other's index. This is the classic way to send commands to an audio or render thread.

cpp · try it yourself
#include <array>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <iostream>
#include <thread>

template <typename T, std::size_t N>
class SpscQueue {
    static_assert((N & (N - 1)) == 0, "capacity must be a power of two");
public:
    bool push(const T& value) {                                   // producer thread only
        std::size_t head = head_.load(std::memory_order_relaxed);
        std::size_t tail = tail_.load(std::memory_order_acquire);
        if (head - tail == N) return false;                         // full
        slots_[head & (N - 1)] = value;
        head_.store(head + 1, std::memory_order_release);           // publish the slot
        return true;
    }
    bool pop(T& out) {                                            // consumer thread only
        std::size_t tail = tail_.load(std::memory_order_relaxed);
        std::size_t head = head_.load(std::memory_order_acquire);
        if (tail == head) return false;                             // empty
        out = slots_[tail & (N - 1)];
        tail_.store(tail + 1, std::memory_order_release);           // free the slot
        return true;
    }
private:
    std::array<T, N> slots_{};
    alignas(64) std::atomic<std::size_t> head_{0};                 // separate cache lines: see below
    alignas(64) std::atomic<std::size_t> tail_{0};
};

struct AudioCommand { std::uint32_t soundId; float volume; };

int main() {
    SpscQueue<AudioCommand, 64> queue;           // much smaller than the number of commands
    const int kCommands = 10000;

    std::thread audioThread([&] {
        std::uint64_t idSum = 0; int received = 0; double volumeSum = 0;
        AudioCommand cmd;
        while (received < kCommands) {
            if (queue.pop(cmd)) { idSum += cmd.soundId; volumeSum += cmd.volume; received++; }
            else std::this_thread::yield();
        }
        std::cout << "audio thread received " << received << " commands, id sum " << idSum
                  << ", volume sum " << volumeSum << "\n";
    });

    for (int i = 1; i <= kCommands; i++) {
        AudioCommand cmd{std::uint32_t(i), 0.5f};
        while (!queue.push(cmd)) std::this_thread::yield();         // full: let the consumer catch up
    }
    audioThread.join();
    std::cout << "expected id sum " << (std::uint64_t(kCommands) * (kCommands + 1) / 2) << "\n";
}
audio thread received 10000 commands, id sum 50005000, volume sum 5000
expected id sum 50005000

Every command arrives exactly once and in order, although the queue only holds 64 at a time. How often the producer found the queue full depends on scheduling, so the program does not print it.

Note: head and tail only ever grow; the slot index is head & (N - 1). With a power-of-two capacity and unsigned arithmetic, head - tail stays correct even when the counters wrap around after 2^64 operations.

Compare-exchange

With several producers, two threads can read the same head and both write the same slot. Multi-producer structures use a compare-exchange loop: read the current value, compute the new one, and swap it in only if nobody changed it meanwhile; otherwise retry. Here several threads report their worst frame into a shared "maximum" without a lock:

cpp · try it yourself
#include <atomic>
#include <iostream>
#include <thread>
#include <vector>

void atomicMax(std::atomic<int>& target, int value) {
    int current = target.load(std::memory_order_relaxed);
    while (value > current &&
           !target.compare_exchange_weak(current, value, std::memory_order_relaxed)) {
        // on failure, `current` is reloaded with the latest value; loop and compare again
    }
}

int main() {
    std::atomic<int> worstFrameUs{0};
    std::vector<std::thread> threads;
    for (int t = 0; t < 4; t++) {
        threads.emplace_back([t, &worstFrameUs] {
            for (int i = 0; i < 1000; i++) atomicMax(worstFrameUs, (i * 37 + t * 101) % 16000);
        });
    }
    for (auto& th : threads) th.join();
    std::cout << "worst frame: " << worstFrameUs.load() << " us\n";
}
worst frame: 15995 us

Lock-free multi-producer queues are much harder than this: the ABA problem (a value changes from A to B and back, so a compare-exchange wrongly succeeds) and safe memory reclamation (when can a popped node be freed?) are research topics. Use a proven implementation such as moodycamel's ConcurrentQueue, or a mutex, and measure.

False sharing

CPUs move memory between cores in cache lines, 64 bytes on x86-64 and most ARM chips (128 on Apple's M-series for some purposes). If two threads write two different variables that happen to sit in the same line, each write invalidates the other core's copy and the line ping-pongs between cores. Nothing is logically shared, yet the code runs as if it were: that is false sharing. A per-thread counter array is the classic victim.

The fix is layout, not locking: give each hot, independently written value its own line with alignas(64) (or std::hardware_destructive_interference_size from <new>, available in GCC 12+ and recent MSVC/Clang). We can check the layout directly:

cpp · try it yourself
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <iostream>

struct CountersPacked {
    std::atomic<std::uint64_t> perThread[4];
};

struct alignas(64) PaddedCounter {
    std::atomic<std::uint64_t> value;
};
struct CountersPadded {
    PaddedCounter perThread[4];
};

template <typename T>
void report(const char* name, const T& c) {
    auto base = reinterpret_cast<std::uintptr_t>(&c);
    std::cout << name << ": sizeof " << sizeof(T) << ", alignof " << alignof(T) << "\n";
    for (int i = 0; i < 4; i++) {
        auto addr = reinterpret_cast<std::uintptr_t>(&c.perThread[i]);
        std::size_t offset = addr - base;
        std::cout << "  counter " << i << " at offset " << offset << ", cache line " << offset / 64 << "\n";
    }
}

int main() {
    alignas(64) CountersPacked packed{};
    CountersPadded padded{};
    report("packed", packed);
    report("padded", padded);
}
packed: sizeof 32, alignof 8
  counter 0 at offset 0, cache line 0
  counter 1 at offset 8, cache line 0
  counter 2 at offset 16, cache line 0
  counter 3 at offset 24, cache line 0
padded: sizeof 256, alignof 64
  counter 0 at offset 0, cache line 0
  counter 1 at offset 64, cache line 1
  counter 2 at offset 128, cache line 2
  counter 3 at offset 192, cache line 3

All four packed counters share cache line 0, so four threads incrementing "their own" counter fight over one line. The padded version costs 256 bytes instead of 32 and gives each counter its own line. The SpscQueue above uses the same trick for head_ and tail_, which are written by different threads.

Tip: Better than padding: don't share at all. Let each job accumulate into a local variable and write the result once at the end, as the job system examples do. Then use a profiler that shows cache misses (VTune, AMD uProf, perf c2c on Linux) to confirm a suspected false-sharing problem before reorganizing data for it.

Test yourself

In the SPSC queue, why does the producer store head with memory_order_release?

  1. To make the store faster
  2. So the consumer, after an acquire load of head, is guaranteed to see the slot data written before it
  3. To prevent the consumer from reading head
  4. Because relaxed stores are not atomic

What is false sharing?

  1. Two threads reading the same variable
  2. Threads writing different variables that share one cache line, causing the line to bounce between cores
  3. A race condition on a shared counter
  4. Sharing a mutex between two classes

What does a failed compare_exchange_weak(current, value) do to current?

  1. Leaves it unchanged
  2. Sets it to value
  3. Loads the atomic's latest value into it
  4. Sets it to zero