RPN Calculator and Lock-Free Queue Implementation
Data Structure DesignModel answerLast updated
Build a macro-enabled expression evaluator and implement a thread-safe ring buffer with proper memory ordering.
You're building performance-critical components for a financial system. This exercise covers expression evaluation, lock-free concurrency primitives, and cache-aware design.
Problem 1: Expression Evaluator with Definitions
Build an evaluator for postfix (Reverse Polish) expressions that handles:
- Basic integer operations:
+,-,*,/(integer division) - User-defined shortcuts:
DOUBLE x := x x +lets users write5 DOUBLEinstead of5 5 +
When a shortcut is invoked, arguments are popped from the evaluation stack and substituted into the definition.
Your tasks:
- Choose a data structure for storing shortcuts with efficient lookup
- Describe your evaluation algorithm
- Explain how you prevent infinite expansion (e.g.,
A := A 1 +)
Problem 2: Single-Producer Single-Consumer Queue
Implement a fixed-size circular buffer for passing messages between exactly two threads—one writer, one reader—without locks.
Requirements:
- Use C++ atomics with explicit memory ordering
- Size must be a power of two
- Provide
push(T value) -> boolandpop(T& out) -> boolmethods - Explain your choice of memory orderings (
relaxed,acquire,release,seq_cst)
Problem 3: Cache Line Optimization
False sharing occurs when two threads modify variables that share a cache line, causing unnecessary synchronization at the hardware level.
For your queue implementation:
- Identify which variables are at risk
- Show how to use alignment directives to place them on separate cache lines
- Explain why this matters for performance
Problem 4: Custom Allocator Design
Design a memory allocator for objects of fixed size T where:
- Thread A allocates objects
- Thread B deallocates them
- You want to avoid
malloc/freeoverhead
Describe your approach to handle cross-thread deallocation efficiently while avoiding contention.
Hints
Hint 1
For the evaluator: a hash table gives O(1) average lookup; track expansion depth per token to detect cycles
Hint 2
For the queue: only the producer modifies the write index, only the consumer modifies the read index—no atomic read-modify-write needed
Hint 3
Cache lines are typically 64 bytes; use alignas(64) to force variables onto separate lines
Hint 4
For the allocator: consider a thread-local freelist that the deallocating thread can return objects to via a lock-free queue
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Problem 1: Expression Evaluator with Definitions
Data Structure Choice
Use a hash map (e.g., std::unordered_map<std::string, Definition>) where each definition stores:
- Parameter names as a list
- Body tokens as a list
Hash maps provide O(1) average-case lookup. If you need deterministic worst-case bounds or ordered traversal, a balanced tree (std::map) gives O(log N).
Evaluation Algorithm
Use two stacks:
- Value stack: holds intermediate integer results
- Work stack: holds tokens awaiting processing, each tagged with its expansion depth
Process tokens iteratively:
- Integer literal: push to value stack
- Operator (
+,-,*,/): pop two values, compute, push result - Defined shortcut: pop required arguments, substitute into body, push body tokens onto work stack with
depth + 1
This avoids using call-stack recursion, which would be harder to bound.
Preventing Infinite Expansion
Two safeguards:
-
Depth limit: Each token on the work stack carries its expansion depth. If depth exceeds a threshold (e.g., 64), raise an error. This catches direct recursion (
A := A 1 +) and mutual recursion (A := B,B := A). -
Token budget: Even non-recursive definitions can cause exponential blowup (
A := B B,B := C C, ...). Cap the total tokens processed (e.g., 1 million) to bound CPU and memory.
Alternatively, build a dependency graph at definition time and reject cycles with DFS, but this only works if definitions must precede usage.
Complexity
- Lookup per token: O(1) amortized
- Expanding a definition: O(body length)
- Overall: O(total expanded tokens), bounded by the token budget
Edge Cases
- Stack underflow (not enough operands for an operator or shortcut)
- Leftover values after processing (incomplete expression)
- Division by zero
- Negative literals like
-5vs. the subtraction operator - Redefining existing shortcuts (typically last definition wins)
Sample Implementation (Python)
class Evaluator:
def __init__(self, max_depth=64, max_tokens=1_000_000):
self.shortcuts = {} # name -> (params, body_tokens)
self.max_depth = max_depth
self.max_tokens = max_tokens
def define(self, text: str):
# Parse "NAME param1 ... := body tokens"
left, _, right = text.partition(":=")
parts = left.split()
name, params = parts[0], parts[1:]
self.shortcuts[name] = (params, right.split())
def eval(self, expr: str) -> int:
values = []
work = [(tok, 0) for tok in reversed(expr.split())]
processed = 0
while work:
if processed >= self.max_tokens:
raise RuntimeError("token budget exceeded")
processed += 1
tok, depth = work.pop()
if tok.lstrip('-').isdigit():
values.append(int(tok))
elif tok in {'+', '-', '*', '/'}:
if len(values) < 2:
raise ValueError(f"not enough operands for {tok}")
b, a = values.pop(), values.pop()
if tok == '+': values.append(a + b)
elif tok == '-': values.append(a - b)
elif tok == '*': values.append(a * b)
else:
if b == 0: raise ZeroDivisionError()
values.append(int(a / b)) # truncate toward zero
elif tok in self.shortcuts:
if depth >= self.max_depth:
raise RecursionError(f"expansion depth exceeded at {tok}")
params, body = self.shortcuts[tok]
if len(values) < len(params):
raise ValueError(f"not enough arguments for {tok}")
args = {p: str(values.pop()) for p in reversed(params)}
for t in reversed(body):
work.append((args.get(t, t), depth + 1))
else:
raise ValueError(f"unknown token: {tok}")
if len(values) != 1:
raise ValueError("incomplete expression")
return values[0]
Problem 2: SPSC Lock-Free Queue
Design Principles
- Single ownership: only the producer writes the tail index; only the consumer writes the head index
- Free-running counters: indices are unsigned integers that wrap around naturally
- Power-of-two size: enables efficient modulo via bitwise AND (
index & (N-1)) - Count calculation:
tail - headalways gives the correct item count due to unsigned arithmetic
Memory Ordering Rationale
Release/acquire pairs establish happens-before relationships:
- Producer: writes data to buffer slot (1), then publishes by incrementing tail with
release(2). The release ensures the data write is visible before the tail update. - Consumer: reads tail with
acquire(1), ensuring it sees all data writes that happened before the producer's release. After consuming, it frees the slot by incrementing head withrelease(2).
Relaxed loads are safe when accessing thread-local cached copies because there's no cross-thread synchronization at that moment.
Implementation
template<typename T, size_t N>
class SPSCQueue {
static_assert((N & (N - 1)) == 0, "N must be power of 2");
alignas(64) std::atomic<size_t> head_{0}; // consumer writes
alignas(64) size_t head_cache_{0}; // producer's cache
alignas(64) std::atomic<size_t> tail_{0}; // producer writes
alignas(64) size_t tail_cache_{0}; // consumer's cache
alignas(64) T buffer_[N];
public:
bool push(const T& item) { // producer only
size_t t = tail_.load(std::memory_order_relaxed);
size_t next = t + 1;
if (next - head_cache_ > N) { // might be full
head_cache_ = head_.load(std::memory_order_acquire);
if (next - head_cache_ > N) return false; // actually full
}
buffer_[t & (N - 1)] = item;
tail_.store(next, std::memory_order_release);
return true;
}
bool pop(T& item) { // consumer only
size_t h = head_.load(std::memory_order_relaxed);
if (h == tail_cache_) { // might be empty
tail_cache_ = tail_.load(std::memory_order_acquire);
if (h == tail_cache_) return false; // actually empty
}
item = buffer_[h & (N - 1)];
head_.store(h + 1, std::memory_order_release);
return true;
}
};
Why not seq_cst? Sequential consistency provides a total global order but is expensive. Release/acquire gives sufficient ordering guarantees for this pattern at lower cost.
Problem 3: Cache Line Optimization
The Problem
Modern CPUs have cache coherence protocols (e.g., MESI). When thread A modifies a variable, any cache line containing that variable is invalidated in other cores' caches. If head_ and tail_ share a cache line:
- Producer updates
tail_→ invalidates consumer's cache - Consumer updates
head_→ invalidates producer's cache - This ping-pong happens even though they're modifying different variables
This is false sharing.
Solution
Place each atomic counter on its own cache line using alignas:
alignas(64) std::atomic<size_t> head_;
alignas(64) std::atomic<size_t> tail_;
Cache lines are typically 64 bytes. C++17 provides std::hardware_destructive_interference_size, but 64 is a safe portable choice.
Also align cached copies and the buffer array to avoid further false sharing.
Performance Impact
In microbenchmarks, fixing false sharing can improve throughput by 2–10× depending on update frequency and CPU architecture. In real systems, the impact depends on contention level.
Problem 4: Cross-Thread Allocator
Challenge
Thread A allocates, thread B deallocates. A simple shared freelist requires locking on both operations. We want to avoid that.
Design
Per-thread freelists with a return queue:
- Thread A maintains a thread-local freelist of available slots
- When A allocates:
- If freelist is non-empty, pop and return
- Otherwise, allocate a new chunk (e.g., 64 objects at once from system allocator)
- When thread B deallocates:
- Push the object to a lock-free SPSC queue that feeds back to thread A
- Periodically (e.g., when A's freelist is empty or on allocation), A drains the return queue into its freelist
Benefits
- No locks on the hot path: A allocates from thread-local state
- Bounded contention: The return queue is only touched during deallocation, which is typically less frequent
- Bulk operations: Draining the return queue in batches amortizes cache coherence costs
Memory Overhead
Each chunk wastes some metadata. With 64-object chunks and 64-byte objects, overhead is ~0.1%.
Alternative: Hazard Pointers
For more complex scenarios (multiple deallocating threads), hazard pointers or epoch-based reclamation provide safe memory reuse without ABA problems, but add complexity.
Common Mistakes
- Evaluator: Using host-language recursion makes depth limits hard to enforce
- Queue: Using
seq_csteverywhere is correct but slower than needed - Cache: Forgetting to align the buffer array itself, not just the indices
- Allocator: Returning freed objects directly to a global pool creates lock contention
The key themes are clear ownership boundaries, minimal synchronization, and hardware-aware layout.