Postfix Macro Evaluation and Lock-Free C++ Primitives

Easy · Software Engineering Fundamentals · Software Engineer · Technical Screen

Prompt

Walk through the design and C++/systems trade-offs for four connected low-latency building blocks:

  1. Postfix Arithmetic Interpreter with Parameterized Macros: Design a stack-based interpreter for Reverse Polish Notation (postfix) expressions supporting signed integer operations (+, -, *, /) alongside user-defined symbolic macros (for example, CUBE n := n n * n *) that expand during evaluation. Explain which data structures provide O(1) or O(log N) macro lookup, and detail how you guard against direct or mutually recursive macro definitions.
  2. Bounded Lock-Free SPSC Ring Buffer: Implement a fixed-capacity Single-Producer, Single-Consumer circular queue in C++11 whose capacity is a power of two. Write enqueue and dequeue with explicit std::memory_order operations, and explain why publishing data requires memory_order_release on the writer paired with memory_order_acquire on the reader (and symmetrically when freeing slots).
  3. Cache-Line Isolation & False Sharing: Explain how false sharing harms tail latency when the producer and consumer run on separate CPU cores, and show how to structure your queue (using alignas or padding) so head and tail live on separate cache lines.
  4. Cross-Thread Fixed-Size Object Pool: Design a custom pool allocator to replace malloc/free when one thread continuously allocates objects of type T and another thread deallocates them, avoiding both lock contention and memory fragmentation.

Scope & Expectations

  • Compare hash-based, tree-based, and interned-ID macro tables, and avoid exponential memory blowup or stack overflows by using lazy frame-stack evaluation and cycle detection.
  • Show exact C++11 release/acquire synchronization on a power-of-two ring buffer so non-atomic payload reads and writes are race-free without mutexes or atomic read-modify-write instructions.
  • Eliminate multi-core cache-line ping-pong with alignas(64) separation (plus local shadow indices) and recycle cross-thread pooled objects through lock-free batch reclamation.

Step-by-step walkthrough

  1. Part 1a: RPN evaluation and O(1) / O(log N) macro storage

    Reverse Polish Notation (RPN) (also called postfix notation) places operators after their operands — 2 3 + instead of 2 + 3 — so expressions never need parentheses or operator-precedence rules. You scan tokens left to right with an integer stack: numbers push onto the stack, and +, -, *, / pop the right operand first, pop the left operand second, and push left op right (truncating / toward zero like C++, so -9 4 / gives -2).

    A macro definition CUBE n := n n * n * binds a name (CUBE), an ordered parameter list (n), and a token body (n n * n *). Calling CUBE pops one value per parameter from the operand stack (in reverse parameter order, because the last argument was pushed last and sits on top!) and evaluates the body with those parameter names bound.

    Three ways to store macros, depending on latency requirements:

    • Hash table (std::unordered_map<std::string, Macro> in C++ / dict in Python): O(1) average-case lookup (hashing the token string takes O(token length)), with O(N) theoretical worst case under hash collisions.
    • Balanced binary search tree (std::map<std::string, Macro>): Guaranteed O(log N) string comparisons in the worst case and naturally sorted macro listings.
    • Token interning + flat vector (best for ultra-low latency): Interning assigns each unique symbol string a sequential integer ID (0, 1, 2, ...) once at definition/parse time, compiling macro bodies into compact bytecode structs (PUSH 5, ARG 0, MUL, CALL 3). At runtime, macro lookup is macros[id] — worst-case O(1) array indexing with zero string hashing!

    Trace both 2 3 + CUBE (CUBE n := n n * n *) and a two-parameter macro 14 4 DIFF (DIFF p q := p q -) to see why reverse parameter popping matters:

    Trace 1: 2 3 + CUBE                          Trace 2: 14 4 DIFF  (DIFF p q := p q -)
    token  action                    stack       token  action                        stack
    -----  ------------------------  --------    -----  ----------------------------  --------
    2      push 2                    [2]         14     push 14                       [14]
    3      push 3                    [2, 3]      4      push 4 (top)                  [14, 4]
    +      pop 3, pop 2, push 5      [5]         DIFF   pop q=4 first, then pop p=14  []
    CUBE   pop n=5, enter body       []            p    push bound p=14               [14]
      n    push bound n=5            [5]           q    push bound q=4                [14, 4]
      n    push bound n=5            [5, 5]        -    pop right=4, left=14 -> 10    [10]
      *    pop 5, pop 5, push 25     [25]
      n    push bound n=5            [25, 5]
      *    pop 5, pop 25, push 125   [125]
    
  2. Part 1b: Lazy frame-stack expansion and cycle rejection

    Why naive string replacement fails. Rewriting macro names into strings before evaluation (eager textual expansion) blows up memory exponentially even without recursion! Consider D0 := 1, D1 := D0 D0 +, ..., D40 := D39 D39 +: just 40 tiny definitions expand to more than 2^40 (over a trillion) tokens in RAM, and a recursive macro loops forever during expansion.

    Instead, expand lazily with an explicit frame stack (frames: list[Frame]), where each Frame holds (tokens, pos, bindings):

    • Memory stays O(active nesting depth) rather than O(total expanded tokens), and because we manage frames on the heap/array instead of using C++/Python function recursion, deep macros can never crash the process with a native call-stack overflow.
    • Reject cycles at definition time. Because our RPN language has no if/branch operator, any macro that can reach itself (directly like A := A 1 +, or indirectly like A := B and B := A 1 +) is guaranteed to loop forever! When defining NAME, perform a quick graph walk (_reaches) over referenced macros (ignoring tokens shadowed by parameter names) and reject any cycle immediately.
    • Enforce both max_depth and max_steps budgets. D40 above has no cycle and uses only 42 stack frames, yet executes 4 * 2^40 - 3 steps — so max_depth caps memory while max_steps caps CPU time.
    import re
    
    INTEGER = re.compile(r"-?[0-9]+")
    NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
    OPERATORS = {"+", "-", "*", "/"}
    
    
    class RpnError(Exception):
        pass
    
    
    class Frame:
        def __init__(self, tokens, bindings):
            self.tokens = tokens        # tuple of body tokens (or top-level expression)
            self.pos = 0                # index of next token to execute in this frame
            self.bindings = bindings    # dict mapping param_name -> int for this call
    
    
    def apply_operator(op, left, right):
        if op == "+":
            return left + right
        if op == "-":
            return left - right
        if op == "*":
            return left * right
        if right == 0:
            raise RpnError("division by zero")
        quotient = abs(left) // abs(right)  # truncate toward zero to match C++ integer division
        return -quotient if (left < 0) != (right < 0) else quotient
    
    
    class RpnEvaluator:
        def __init__(self, max_depth=64, max_steps=1_000_000):
            self.macros = {}            # macro_name -> (params_tuple, body_tokens_tuple)
            self.max_depth = max_depth
            self.max_steps = max_steps
    
        def define(self, line):
            """Parse 'NAME p1 p2 := body' and reject direct or indirect recursion cycles."""
            head, sep, body = line.partition(":=")
            names = head.split()
            if not sep or not names or not all(NAME.fullmatch(n) for n in names):
                raise RpnError(f"invalid macro definition: {line!r}")
            name, params = names[0], tuple(names[1:])
            if len(set(params)) != len(params):
                raise RpnError(f"duplicate parameter name in {line!r}")
            body_tokens = tuple(body.split())
            if self._reaches(body_tokens, params, name):
                raise RpnError(f"recursive macro cycle detected for {name!r}")
            # Store immutable tuples so redefining a macro never mutates an in-flight Frame.
            self.macros[name] = (params, body_tokens)
    
        def _reaches(self, tokens, params, target):
            """Return True if expanding `tokens` can transitively invoke macro `target`."""
            pending = [t for t in tokens if t not in params]
            visited = set()
            while pending:
                tok = pending.pop()
                if tok == target:
                    return True
                if tok in visited or tok not in self.macros:
                    continue
                visited.add(tok)
                inner_params, inner_body = self.macros[tok]
                for inner_tok in inner_body:
                    if inner_tok not in inner_params:
                        pending.append(inner_tok)
            return False
    
        def evaluate(self, expression):
            stack = []
            frames = [Frame(tuple(expression.split()), {})]
            steps = 0
            while frames:
                frame = frames[-1]
                if frame.pos == len(frame.tokens):
                    frames.pop()
                    continue
                token = frame.tokens[frame.pos]
                frame.pos += 1
                steps += 1
                if steps > self.max_steps:
                    raise RpnError("evaluation step budget exceeded")
    
                if token in frame.bindings:
                    stack.append(frame.bindings[token])
                elif INTEGER.fullmatch(token):
                    stack.append(int(token))
                elif token in OPERATORS:
                    if len(stack) < 2:
                        raise RpnError(f"operator {token!r} needs two operands")
                    right = stack.pop()
                    left = stack.pop()
                    stack.append(apply_operator(token, left, right))
                elif token in self.macros:
                    params, body = self.macros[token]
                    if len(stack) < len(params):
                        raise RpnError(f"macro {token!r} needs {len(params)} arguments")
                    if len(frames) >= self.max_depth:
                        raise RpnError("macro nesting depth limit exceeded")
                    # Last parameter sits on top of the stack, so pop parameters in reverse order.
                    bindings = {}
                    for param in reversed(params):
                        bindings[param] = stack.pop()
                    frames.append(Frame(body, bindings))
                else:
                    raise RpnError(f"unknown token {token!r}")
    
            if len(stack) != 1:
                raise RpnError(f"expected single result on stack, got {stack}")
            return stack[0]
    
  3. Part 2a: Lock-free SPSC ring buffer with power-of-two masking

    A Single-Producer, Single-Consumer (SPSC) queue connects exactly one writer thread to one reader thread over a fixed circular array of Capacity slots (where Capacity is a power of two, such as 64 or 1024). Because only the producer modifies tail_ (next write count) and only the consumer modifies head_ (next read count), neither thread ever needs a mutex or an expensive read-modify-write compare-and-swap (CAS) instruction — plain atomic loads and stores are enough!

    Instead of wrapping head_ and tail_ back to 0 at Capacity, let both std::size_t counters increase monotonically (0, 1, 2, ...) and mask only when indexing the array (index & (Capacity - 1)):

    Capacity = 8 (kMask = 7):   suppose head_ = 13 (slot 13 & 7 = 5),  tail_ = 21 (slot 21 & 7 = 5)
    Items currently in queue:   tail_ - head_ = 21 - 13 = 8 == Capacity  -->  FULL (all 8 slots used!)
    If consumer reads all 8:    head_ becomes 21, tail_ - head_ = 0      -->  EMPTY!
    

    Keeping counters monotonic eliminates the classic "does head == tail mean empty or full?" ambiguity without wasting a dummy slot, and because 2^64 is divisible by every power-of-two Capacity, unsigned subtraction tail - head remains exact even across 64-bit wrap-around (which at 1 billion ops/sec takes 584 years).

    #include <atomic>
    #include <cstddef>
    
    template <typename T, std::size_t Capacity>
    class SpscQueueBasic {
        static_assert(Capacity >= 2 && (Capacity & (Capacity - 1)) == 0, "Capacity must be a power of 2");
        static constexpr std::size_t kMask = Capacity - 1;
    
    public:
        bool enqueue(const T& item) {                                        // called ONLY by producer
            const std::size_t tail = tail_.load(std::memory_order_relaxed);  // only producer writes tail_
            const std::size_t head = head_.load(std::memory_order_acquire);  // sync with consumer's release
            if (tail - head == Capacity) return false;                       // queue is full
            buffer_[tail & kMask] = item;                                    // Step 1: write payload to slot
            tail_.store(tail + 1, std::memory_order_release);                // Step 2: publish new tail_
            return true;
        }
    
        bool dequeue(T& out) {                                               // called ONLY by consumer
            const std::size_t head = head_.load(std::memory_order_relaxed);  // only consumer writes head_
            const std::size_t tail = tail_.load(std::memory_order_acquire);  // sync with producer's release
            if (tail == head) return false;                                  // queue is empty
            out = buffer_[head & kMask];                                     // Step 1: read payload from slot
            head_.store(head + 1, std::memory_order_release);                // Step 2: mark slot free
            return true;
        }
    
    private:
        std::atomic<std::size_t> head_{0};
        std::atomic<std::size_t> tail_{0};
        T buffer_[Capacity];
    };
    
  4. Part 2b: Why release and acquire barriers are both mandatory

    buffer_[slot] is a plain non-atomic variable! Without memory-ordering barriers, both the C++ compiler and weakly ordered CPUs (such as ARM64) are free to reorder memory reads and writes across different addresses as long as single-threaded logic looks unchanged.

    C++11's release-acquire synchronization establishes a guaranteed happens-before timeline between the two cores:

    Producer Thread                                        Consumer Thread
    ----------------------------------------------         ----------------------------------------------
    1. buffer_[slot] = item;   (ordinary write)
    2. tail_.store(t + 1, release);  --- synchronizes ---> 3. tail_.load(acquire) sees (t + 1)
       [nothing above #2 can sink below #2]                   [nothing below #3 can float above #3]
                                                           4. out = buffer_[slot];  (guaranteed to see #1!)
    
    • Why producer needs memory_order_release on tail_.store: Prevents the compiler or CPU store buffer from publishing tail + 1 before buffer_[slot] = item finishes becoming visible. Without release, the consumer can observe tail + 1 and read uninitialized garbage from buffer_[slot].
    • Why consumer needs memory_order_acquire on tail_.load: Prevents the compiler or CPU out-of-order load unit from speculatively reading buffer_[slot] before reading tail_.
    • Why the reverse pair (head_.store(release) -> head_.load(acquire)) is equally required: Guarantees the consumer finishes copying out = buffer_[slot] before the producer sees head_ advance on the next lap around the ring and overwrites that same slot!
    • Why relaxed works for a thread's own index, and why seq_cst is overkill: Producer is the sole writer of tail_, so its own tail_.load(relaxed) always sees its latest value. Full sequential consistency (memory_order_seq_cst) emits an expensive full memory fence (xchg / mfence on x86-64), whereas acquire loads and release stores compile to zero-overhead mov instructions on x86-64 and lightweight ldar/stlr instructions on ARM64.
  5. Part 3: Eliminating false sharing with cache-line alignment and index caching

    CPU cores do not share individual bytes — their L1/L2 caches trade memory in fixed cache lines (64 bytes on x86-64 and most server ARM CPUs; 128 bytes on Apple Silicon). False sharing occurs when two independent variables modified by different cores (head_ and tail_) sit inside the same 64-byte cache line:

    BAD (shared 64B line):   [ head_ (8B) | tail_ (8B) | buffer_[0..5] ... ]
      Producer writes tail_ -> invalidates Consumer's L1 line -> Consumer stalls ~40-80 ns re-fetching head_!
    
    GOOD (alignas(64) per writer + local shadow index):
      Cache line 0 (Consumer-owned): [ head_ (8B) | cached_tail_ (8B) | 48B padding ]
      Cache line 1 (Producer-owned): [ tail_ (8B) | cached_head_ (8B) | 48B padding ]
      Cache line 2+ (Ring payload):  [ buffer_[0] | buffer_[1] | ...                ]
    

    Notice the second win unlocked by separating the lines: the producer stores a non-atomic shadow copy cached_head_ on its own cache line and only reads the consumer's head_ atomic when tail - cached_head_ == Capacity (the queue appears full)! Symmetrically, the consumer caches cached_tail_ on its own line and only reloads tail_ when head == cached_tail_. In steady-state traffic, enqueue and dequeue avoid cross-core index traffic on almost every call:

    #include <atomic>
    #include <cstddef>
    
    template <typename T, std::size_t Capacity>
    class SpscQueue {
        static_assert(Capacity >= 2 && (Capacity & (Capacity - 1)) == 0, "Capacity must be a power of 2");
        static constexpr std::size_t kMask = Capacity - 1;
        static constexpr std::size_t kCacheLine = 64;  // use 128 on CPUs with adjacent-line spatial prefetchers
    
    public:
        bool enqueue(const T& item) {                                        // producer thread only
            const std::size_t tail = tail_.load(std::memory_order_relaxed);
            if (tail - cached_head_ == Capacity) {                           // shadow says full -> refresh once
                cached_head_ = head_.load(std::memory_order_acquire);
                if (tail - cached_head_ == Capacity) return false;           // genuinely full
            }
            buffer_[tail & kMask] = item;
            tail_.store(tail + 1, std::memory_order_release);
            return true;
        }
    
        bool dequeue(T& out) {                                               // consumer thread only
            const std::size_t head = head_.load(std::memory_order_relaxed);
            if (head == cached_tail_) {                                      // shadow says empty -> refresh once
                cached_tail_ = tail_.load(std::memory_order_acquire);
                if (head == cached_tail_) return false;                      // genuinely empty
            }
            out = buffer_[head & kMask];
            head_.store(head + 1, std::memory_order_release);
            return true;
        }
    
    private:
        // Consumer-written state isolated on its own 64-byte cache line:
        alignas(kCacheLine) std::atomic<std::size_t> head_{0};
        std::size_t cached_tail_ = 0;
    
        // Producer-written state isolated on its own 64-byte cache line:
        alignas(kCacheLine) std::atomic<std::size_t> tail_{0};
        std::size_t cached_head_ = 0;
    
        // Ring slots start on a fresh cache line so buffer_[0] never shares a line with tail_/cached_head_:
        alignas(kCacheLine) T buffer_[Capacity];
    };
    

    (Note: Never place cached_head_ on head_'s line — the producer writes cached_head_, which would reintroduce false sharing on head_!)

  6. Part 4: Lock-free cross-thread pool allocator without contention or fragmentation

    When Thread A continually allocates T objects and Thread B frees them, standard malloc/free hits a worst-case asymmetric pattern: Thread B's local allocator cache fills up and has to flush batches back to a central mutex-guarded heap while Thread A's cache keeps running dry.

    Eliminate both locks and fragmentation with single-owner private allocation + SPSC batch reclamation:

      [Thread A: Allocator Owner]                                    [Thread B: Consumer / Releaser]
      +-------------------------+    1. allocate(): pop free_[]      +-----------------------------+
      | slots_[N] (preallocated)|  ------------------------------->  | uses T*, then calls         |
      | free_[N]  (non-atomic!) |                                    | release(obj): ~T() +        |
      +-------------------------+  <-------------------------------  | returned_.enqueue(slot)     |
            ^                        2. reclaim() when free_ empty   +-----------------------------+
            +----------- drains SpscQueue<Slot*, N> in a fast batch
    
    • Zero fragmentation: Every slot is identically sized (sizeof(T), cache-line aligned via alignas(64) so live objects on different threads never false-share). Any free slot satisfies any allocation — external fragmentation is mathematically zero!
    • Zero lock contention: Thread A pops from a plain non-atomic array free_[--free_count_] in ~2 cycles. Thread B never touches free_[]; it calls object->~T() and pushes the raw Slot* onto returned_ (SpscQueue<Slot*, N>). Because at most N slots exist, returned_ (Capacity = N, a power of two) can never overflow! Only when free_count_ == 0 does Thread A drain returned_ back into free_[] in one tight loop. (If multiple threads free objects allocated by Thread A, replace returned_ with a lock-free MPSC Treiber stack where releasers CAS-push and Thread A steals the whole chain atomically via head.exchange(nullptr, acquire) — avoiding single-pop ABA bugs, where a node is popped, reused, and pushed back under the same pointer address).
    #include <cstddef>
    #include <new>
    #include <utility>
    
    template <typename T, std::size_t N>
    class CrossThreadPool {
        static_assert(N >= 2 && (N & (N - 1)) == 0, "N must be a power of 2 for SpscQueue");
    
        struct alignas(64) Slot {  // 64B alignment prevents false sharing between adjacent live T objects
            alignas(T) unsigned char bytes[sizeof(T)];
        };
    
    public:
        CrossThreadPool() {
            for (std::size_t i = 0; i < N; ++i) {
                free_[i] = &slots_[i];
            }
            free_count_ = N;
        }
    
        template <typename... Args>
        T* allocate(Args&&... args) {                                // Thread A (owner) only
            if (free_count_ == 0) reclaim();
            if (free_count_ == 0) return nullptr;                    // pool exhausted: apply back-pressure
            Slot* slot = free_[free_count_ - 1];
            // Construct via placement new before decrementing free_count_ so a throwing T() never leaks a slot.
            T* obj = new (slot->bytes) T(std::forward<Args>(args)...);
            --free_count_;
            return obj;
        }
    
        void release(T* object) {                                    // Thread B (releaser) only
            if (object == nullptr) return;
            object->~T();
            returned_.enqueue(reinterpret_cast<Slot*>(object));      // guaranteed true since live objects <= N
        }
    
    private:
        void reclaim() {                                             // batch-drain freed slots back to owner
            Slot* slot = nullptr;
            while (returned_.dequeue(slot)) {
                free_[free_count_++] = slot;
            }
        }
    
        Slot slots_[N];
        Slot* free_[N];                                              // Thread A private stack (zero atomics!)
        std::size_t free_count_ = 0;
        SpscQueue<Slot*, N> returned_;                               // lock-free return pipe from Thread B -> A
    };
    

Intuition & how it works

One unifying systems principle ties all four parts of this problem together: replace hidden runtime magic (recursive call stacks, OS locks, and malloc) with explicit pre-sized arrays where every variable has a single writer. An explicit frame stack lets an RPN macro evaluator expand nested macros without blowing the thread's call stack, and giving a producer thread and consumer thread exclusive write ownership over separate cache-aligned counters lets messages and freed memory slots cross threads with zero locks.

Naive implementations fail in predictable ways under low-latency load. Expanding RPN macros via eager string search-and-replace explodes memory exponentially (2^40 tokens across 40 tiny macro definitions); sharing an unpadded ring buffer causes false sharing (two cores fighting over the same 64-byte cache line even though they touch different variables) or silent data corruption on ARM CPUs when memory_order_relaxed reorders writes; and calling malloc on Thread A + free on Thread B triggers cross-thread heap locks and microsecond-scale OS page faults.

Trace a concrete end-to-end flow: evaluating 2 3 + CUBE (CUBE n := n n * n *) pushes 2, pushes 3, adds to [5], pops n = 5 into a lazy Frame(("n", "n", "*", "n", "*"), {"n": 5}), and computes 125 in O(depth) space. To ship 125 to a consumer thread over an 8-slot SpscQueue (kMask = 7), the producer writes buffer_[tail & 7] = 125 and publishes tail + 1 with memory_order_release; the consumer reads tail with memory_order_acquire, reads 125, and returns the slot (or returns a pooled object via CrossThreadPool::release) without taking a single lock.

Key points

  • RPN macro lookup and lazy expansion. Store macros in a hash map (unordered_map / dict) for O(1) average lookup, an ordered tree (std::map) for O(log N) worst-case lookup, or intern symbol strings into integer IDs at definition time for worst-case O(1) vector indexing. Expand macros lazily on an explicit heap/array Frame stack (popping arguments in reverse parameter order), reject direct and indirect recursion cycles via a graph reachability walk at define() time, and cap both max_depth and max_steps.
  • Monotonic power-of-two SPSC ring. Keep head_ and tail_ as free-running unsigned size_t counters and mask only when indexing (idx & (Capacity - 1)): tail == head is empty, tail - head == Capacity is full, all Capacity slots are usable, and single-writer counters avoid compare-and-swap (CAS).
  • Pairwise release / acquire barriers. Producer writes buffer_[slot] then tail_.store(tail + 1, release), pairing with consumer's tail_.load(acquire) before reading buffer_[slot]. Symmetrically, consumer's head_.store(head + 1, release) pairs with producer's head_.load(acquire) so slots are never overwritten mid-read. Reading a thread's own index uses relaxed.
  • Cache-line isolation + shadow indices. Pad head_ (plus consumer-written cached_tail_) onto one alignas(64) cache line, tail_ (plus producer-written cached_head_) onto a second alignas(64) line, and buffer_ onto a third — eliminating false sharing and avoiding cross-core atomic loads whenever cached indices show space/data available.
  • Zero-contention cross-thread object pool. Preallocate N alignas(64) fixed-size slots owned by Thread A's non-atomic free_[] stack, construct via placement new (new (bytes) T(...), initializing an object inside existing raw memory), and return freed slots from Thread B through SpscQueue<Slot*, N> for amortized batch reclamation with zero external fragmentation.

Common mistakes

  • Expanding RPN macros eagerly by repeated string substitution (exponential 2^k memory blowup on non-recursive DAG chains like Dk := D(k-1) D(k-1) +), or popping multi-parameter macro arguments in forward order instead of reverse stack order.
  • Using native C++ recursion to evaluate macros, letting user input trigger an unrecoverable native stack-overflow segfault (SIGSEGV).
  • Wrapping head_ and tail_ modulo Capacity on store (tail = (tail + 1) & kMask), making head == tail ambiguous between full and empty, or adding a shared size_ counter written by both threads.
  • Using memory_order_relaxed (or C++ volatile, which provides zero multi-core synchronization!) on tail_/head_ handoffs — a bug that appears to "work" on x86-64's strong store order yet silently corrupts messages on ARM64 or under compiler instruction scheduling.
  • Separating head_ and tail_ with alignas(64) while accidentally placing producer-written cached_head_ on head_'s cache line, reintroducing false sharing.
  • Letting Thread B push freed pointers directly onto Thread A's non-atomic free list (data race), or decrementing free_count_ before placement new runs (leaking a slot if T's constructor throws).

Follow-up questions

  • How do you distinguish a completely full ring buffer from an empty one in your SPSC queue, and how does that compare with reserving one unused sentinel slot? If a ring buffer stores wrapped indices in [0, Capacity - 1], head == tail represents both 0 items and Capacity items. The sentinel-slot approach declares the queue full when ((tail + 1) % Capacity) == head, which works for arbitrary (even non-power-of-two) capacities without unsigned wrap concerns, at the cost of permanently wasting 1 slot (Capacity = 1024 holds only 1023 items — painful when sizeof(T) is large). Our free-running unsigned counter approach stores unmasked head_ and tail_ (0, 1, 2, ...): tail - head == 0 is unambiguously empty and tail - head == Capacity is unambiguously full, utilizing 100% of all Capacity slots, with the sole constraint that Capacity must be a power of two so idx & (Capacity - 1) stays continuous across 2^64 unsigned integer wrap-around (avoiding a third option — a shared atomic<size_t> count_ — which forces expensive read-modify-write contention on every call).
  • Suppose the expression language added conditionals and permitted recursive macros — what memory-safety hazards arise, and how would you enforce a hard call-depth ceiling? Allowing recursion introduces four concrete memory hazards: (1) native call-stack overflow (SIGSEGV) if implemented via C++ host recursion; (2) unbounded heap growth / OOM on both the macro Frame stack and the integer operand stack; (3) integer overflow if precomputing expanded token counts; and (4) dangling references / use-after-free in C++ if an active Frame holds a raw reference into std::unordered_map while a nested command redefines or deletes that macro. Mitigate all four by keeping evaluation on an explicit preallocated std::array<Frame, kMaxDepth> (checking depth < kMaxDepth before pushing, plus tail-call frame reuse when a recursive call is the final token of a body), capping operand stack capacity and max_steps, and storing macro bodies behind immutable reference-counted handles (std::shared_ptr<const Body>).
  • Why do ultra-low-latency trading engines avoid general-purpose heap allocation (malloc/new) on the critical path, and how would you structure startup pre-allocation instead? In low-latency trading, tail-latency variance (p99 / p99.9) matters far more than average speed: while malloc's thread-cache fast path takes ~15–30 ns, a slow-path miss acquires arena mutexes, traverses fragmented free lists, or invokes mmap/brk and triggers ~1–5 microsecond OS minor page faults + TLB shootdowns right in the middle of an order decision. To eliminate dynamic allocation completely after startup: (1) preallocate fixed upper-bound object pools, power-of-two ring buffers, flat price-level arrays, and open-addressing hash tables during process initialization; (2) prefault every byte and lock physical RAM via mlockall(MCL_CURRENT | MCL_FUTURE) backed by 2 MB huge pages; (3) ban hidden heap allocators on the hot path (std::string exceeding SSO capacity, std::function heap captures, std::shared_ptr control blocks, std::vector::push_back growth, and C++ throw); and (4) override global operator new in integration/replay builds to abort or increment a failure counter whenever a thread-local on_hot_path flag is active.

Follow-up questions

Similar questions

More Jump Trading interview questions

All 12 Jump Trading questions →