Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Backend Development
11 min read

Lock-Free Queues Aren't Magic: Choose the Right Concurrency Tool for Your Scenario

This article compares locked and lock-free queue implementations in C++, explaining CAS, ABA problems, memory models, and ring buffers, then provides a decision framework based on concurrency volume, latency requirements, and queue capacity, arguing that business flow design outweighs queue choice for most high-concurrency systems.

1. Locked Queues

1.1 Queue Essence: Shared Resource Across Threads

A queue is the intermediary in the producer-consumer model. Producers push data, consumers pull data — ideally without interference. Reality: dozens of threads may simultaneously access the same head/tail pointers and memory. Without synchronization, pointers race, data gets overwritten, and programs crash.

1.2 What Locks Actually Protect

Locks protect three things:

Data consistency : Enqueue involves multiple steps (update tail, write data, increment count). A lock ensures these steps appear atomic to other threads.

Operation atomicity : A full enqueue may span dozens of instructions. The lock bundles them into an indivisible unit.

Memory visibility : Without locks (or other synchronization), a write by thread A may not be visible to thread B due to CPU caches or compiler reordering. Lock release flushes writes; lock acquire ensures visibility.

1.3 Typical Locked Queue Implementation

A simple C++ thread-safe queue uses std::mutex and std::condition_variable:

#include <queue>
#include <mutex>
#include <condition_variable>

template <typename T>
class ThreadSafeQueue {
private:
    std::queue<T> queue_;
    mutable std::mutex mutex_;
    std::condition_variable cv_;
    size_t capacity_; // 0 = unbounded

public:
    explicit ThreadSafeQueue(size_t capacity = 0) : capacity_(capacity) {}

    void push(T value) {
        std::unique_lock<std::mutex> lock(mutex_);
        if (capacity_ > 0) {
            cv_.wait(lock, [this] { return queue_.size() < capacity_; });
        }
        queue_.push(std::move(value));
        cv_.notify_one();
    }

    bool pop(T& value) {
        std::unique_lock<std::mutex> lock(mutex_);
        cv_.wait(lock, [this] { return !queue_.empty(); });
        value = std::move(queue_.front());
        queue_.pop();
        cv_.notify_one();
        return true;
    }
};

Coarse-grained locking protects the whole function. Fine-grained locking (separate locks for head/tail) adds complexity with uncertain gains. Two capacity shapes: unbounded (linked list, dynamic allocation per enqueue) and bounded (ring buffer, fixed capacity). High-frequency trading prefers bounded queues — dynamic allocation's unpredictability is unacceptable at nanosecond scales.

1.4 Where Lock Contention Hurts

Uncontended lock acquire/release: tens to ~100 ns. Contended: triggers futex syscall, kernel transition, hundreds of ns to µs. Two hidden costs:

Cache Miss : Thread A on core 1 modifies head; thread B on core 2 reads it. If the cache line isn't in core 2's cache, it fetches from core 1 or main memory — hundreds of ns lost.

Thread Starvation : Under high contention, some threads may never acquire the lock — a correctness issue, not just performance.

But these overheads are acceptable in the vast majority of scenarios . At thousands to tens of thousands ops/sec, lock overhead is negligible. Spending two weeks on a lock-free queue for <5% gain is rarely worth it.

2. Lock-Free Queues — No Locks, Then What?

2.1 Pessimistic Locking to Optimistic Concurrency Control

Locked = pessimistic: assume conflict, lock first. Lock-free = optimistic: assume no conflict, proceed, retry on failure. Optimism works only when conflicts are rare; frequent conflicts turn retries into CPU-spinning worse than locks.

2.2 Atomic Operations and CAS

Core primitive: Compare-And-Swap (CAS). Logic: "If variable == expected, set to desired; else tell me current value." Single CPU instruction, atomic. x86: cmpxchg. C++11: std::atomic:

std::atomic<int> value{0};

void cas_demo() {
    int expected = 0;
    int desired = 42;
    // If value == expected, set to desired, return true
    // Else update expected to current value, return false
    bool success = value.compare_exchange_weak(expected, desired);
}
compare_exchange_weak

may spuriously fail (return false despite match) on some platforms — loop retry handles this efficiently. _strong guarantees no spurious failure but costs more.

2.3 Lock-Free Pitfalls

ABA Problem : Thread A reads head → node X. Thread B pops X, pushes new node at same address (memory reuse). Thread A's CAS sees same address, succeeds, but data is corrupted. Fix: tag pointers with version numbers (increment on each modification).

Memory Reclamation : In locked queues, pop → delete. Lock-free: can't delete while other threads may still read the node. Solutions: Hazard Pointers, RCU, reference counting — each complex; production-grade memory management alone fills books.

Memory Model : std::memory_order — relaxed fastest but no ordering; seq_cst strictest but slowest. Most cases need only acquire / release pairs.

Your hand-rolled lock-free queue will likely be slower than std::mutex — not because the algorithm is bad, but because subtle bugs (memory model, ABA, reclamation) turn "lock-free" into "infinite bugs."

3. Two Lock-Free Implementation Shapes

3.1 Linked List — Unbounded Queue (Michael-Scott Queue, 1996)

Classic MSQueue uses a dummy node. Head always points to dummy; tail points to last valid node. Enqueue links new node at tail via CAS; dequeue advances head. Simplified core:

template <typename T>
class MSQueue {
private:
    struct Node {
        T data;
        std::atomic<Node*> next;
        Node() : next(nullptr) {}
        Node(const T& val) : data(val), next(nullptr) {}
    };
    std::atomic<Node*> head;
    std::atomic<Node*> tail;

public:
    MSQueue() {
        Node* dummy = new Node();
        head.store(dummy);
        tail.store(dummy);
    }

    void enqueue(const T& val) {
        Node* new_node = new Node(val);
        Node* old_tail = tail.load();
        while (true) {
            Node* next = old_tail->next.load();
            if (next == nullptr) {
                if (old_tail->next.compare_exchange_weak(next, new_node)) {
                    break; // linked successfully
                }
            } else {
                // tail lagging, help advance it
                tail.compare_exchange_weak(old_tail, next);
            }
        }
        tail.compare_exchange_weak(old_tail, new_node);
    }
};

Unbounded, but every enqueue requires new — dynamic allocation is a latency killer in low-latency systems.

3.2 Ring Buffer — Bounded Queue

Pre-allocated contiguous memory, two atomic indices (head, tail) wrapping around. This is what high-frequency trading actually uses.

SPSC (Single Producer Single Consumer) — simplest, fastest, no CAS needed:

template <typename T>
class SPSCRingBuffer {
private:
    std::vector<T> buffer_;
    size_t capacity_;
    std::atomic<size_t> head_{0};
    std::atomic<size_t> tail_{0};

public:
    explicit SPSCRingBuffer(size_t capacity)
        : buffer_(capacity), capacity_(capacity) {}

    bool enqueue(const T& item) {
        size_t tail = tail_.load(std::memory_order_relaxed);
        size_t next = (tail + 1) % capacity_;
        if (next == head_.load(std::memory_order_acquire)) {
            return false; // full
        }
        buffer_[tail] = item;
        tail_.store(next, std::memory_order_release);
        return true;
    }

    bool dequeue(T& item) {
        size_t head = head_.load(std::memory_order_relaxed);
        if (head == tail_.load(std::memory_order_acquire)) {
            return false; // empty
        }
        item = buffer_[head];
        head = (head + 1) % capacity_;
        head_.store(head, std::memory_order_release);
        return true;
    }
};

SPSC uses plain load / store with acquire/release — highest performance tier, bar none.

MPMC (Multi-Producer Multi-Consumer) adds a third cursor (commit). Producers claim a slot (tail), write data, then advance commit so consumers see it. CAS coordinates multiple producers. Complexity is orders of magnitude higher than SPSC.

3.3 Producer-Consumer Pattern Classification

SPSC : Single producer, single consumer. Simplest, fastest, no CAS. If your workload fits — you're golden.

MPSC : Multiple producers, single consumer. Producers need CAS coordination.

SPMC : Single producer, multiple consumers. Consumers coordinate who reads what.

MPMC : Multiple producers, multiple consumers. Most general, most complex. Production libraries like moodycamel::ConcurrentQueue target this.

If SPSC works, never use MPMC — engrave this on every C++ developer's desk.

4. Scenario Decision Guide — Which One Do You Need?

4.1 Ask Yourself Three Questions First

Concurrency volume? Hundreds to thousands ops/sec → locked queue is fine. Tens to hundreds of thousands → consider lock-free, but first check if business flow is the real problem.

Latency requirement? Milliseconds → locked works. Microseconds → locked may still work. Nanoseconds → lock-free needed. True nanosecond requirements exist in <1% of businesses . Many claiming "low latency" actually need 10 ms — locked queues handle that easily.

Fixed or dynamic capacity? Can you predefine max capacity? Yes → prefer fixed ring buffer. No → consider linked list. Fixed buffers: pre-allocated, zero dynamic allocation, cache-friendly, predictable latency. Dynamic resize = allocation + copy + all threads potentially stalled — disaster for low latency.

4.2 When to Use Locked Queues

Moderate concurrency (thousands to tens of thousands ops/sec)

Latency not extreme (milliseconds acceptable)

Business logic complex — lock overhead is tiny fraction

You want maintainable, readable code that won't make colleagues curse you

Locked queues aren't "slow" — they're predictable, stable, battle-tested for decades . You sleep well using them.

4.3 When to Use Lock-Free Queues

Extreme concurrency (hundreds of thousands to millions ops/sec)

Ultra-low latency (microseconds to nanoseconds)

Real-time systems, HFT, game engines, autonomous driving

You accept drastically higher implementation and debugging complexity

You (or your team) genuinely have the expertise to handle lock-free programming

Last two points are often ignored. Many chase "lock-free is fast" without counting the cost.

4.4 The Overlooked Key: Business Flow Design

In financial HFT, bottlenecks are rarely locks — they're bad business flow design.

Business Flow > Locks > Everything Else .

If flow design is sound, locked queues achieve stunning throughput. If flow is broken, nothing helps. Four real-world anti-patterns:

Case 1: Single queue carries mixed-priority tasks — real-time trades, logs, monitoring, stats all in one queue. Low-priority logs block high-priority trades. Fix: separate queues per priority.

Case 2: Severe producer/consumer imbalance — 10 producers, 1 slow consumer. Not a lock problem — consumer capacity problem. Fix: add consumers or batch at producer side.

Case 3: Consumer does I/O — pop then write DB/file (ms to 10s of ms). Lock holds queue for hundreds of ns; real bottleneck is I/O. Fix: consumer only does in-memory work; offload I/O to async thread pool.

Case 4: Cross-core data sharing — producer on core 0, consumer on core 7. Every handoff crosses CPU caches → frequent cache misses. Fix: pin producer/consumer to same core or NUMA node.

None of these are lock problems. Fixing business flow architecture is 10,000x more effective than debating locked vs lock-free.

Real story: HFT firm stuck at 50 µs latency. CTO blamed queue lock, demanded lock-free. perf showed lock contention <5%. Real issue: market data parser → strategy calculator separated by three queues, two thread pools, data hopping across cores 5-6 times. Removed intermediate layers, direct producer-consumer coupling. Latency dropped to 12 µs. Lock unchanged.

5. Performance Comparison

5.1 Locked vs Lock-Free Benchmarks

evpp tests: boost::lockfree::queue 75-150% faster than std::queue + mutex. moodycamel::ConcurrentQueue benchmarks: lock-free 100-500% faster, throughput >70M ops/sec.

HFT project: 10M enqueues — lock-free 12 ms, std::queue + mutex 63 ms.

Looks like lock-free wins? Wait.

Another test: boost::lockfree::queue 15x slower than

std::queue + mutex</strong> on specific hardware. Cause: CAS spinning under high contention burns more CPU than kernel context switches.</p>
<p><strong>Low contention: locked queues can be faster than lock-free.</strong> Data says so.</p>
<p>Lock-free advantage emerges only under high contention, high concurrency. More threads → lock overhead grows → lock-free shines.</p>
<h3>5.2 Counter-Intuitive Fact</h3>
<p><strong>No absolute "better" — only "more suitable."</strong></p>
<p>Locked: stable, predictable performance. Lock-free: spectacular numbers in specific scenarios, but pay with complexity, debugging hell, and unforeseen edge bugs. Seen teams chase 5% gain, introduce lock-free, hit ABA, leaks, data corruption — three production incidents, three rollbacks, back to locked.</p>
<h2>6. Practical Recommendations</h2>
<h3>6.1 Actionable Advice</h3>
<ol>
<li><strong>Measure first, optimize later.</strong> Don't guess. Run <code>perf

, flame graphs. If lock contention <10%, two weeks on lock-free yields near-zero ROI. Prefer mature libraries. If you need lock-free, don't write your own. Use: moodycamel::ConcurrentQueue — most mature, highest-performance C++ lock-free queue. boost::lockfree::queue — Boost official, reliable. atomic_queue — lightweight ring-buffer based. These are battle-tested in production; your from-scratch version won't be. Start with SPSC. If your workload permits single-producer single-consumer, use SPSC. Simplest, fastest, least error-prone. Upgrade to MPMC only when truly needed. Prefer bounded (ring buffer). Pre-allocate memory, eliminate dynamic allocation uncertainty. Linked list flexibility is a virtue in low-frequency; in high-frequency, its unpredictability is fatal.

6.2 Core Takeaways

Locks exist to protect data consistency — they are not innate "performance killers." Locked queues are correct and fast enough for the vast majority of scenarios.

Lock-free trades algorithmic complexity for higher concurrency. You gain lower latency and higher throughput; you lose readability, maintainability, and debuggability.

The most important skill is judging your actual scenario, not blindly chasing "lock-free." Don't turn tech selection into religion. Locked or lock-free — they're tools. Tools aren't good or bad; they're fit or unfit.

For attribution, corrections or content rights, contactadmin@besthub.dev

Report an issue with this article

Discussion 0

Write a comment

Sign in to join the discussion

No public comments on this page. Sign in to comment