KatInterview

RPN Calculator and Lock-Free Queue Implementation

Data Structure DesignModel answer
MediumModel answerData Structure Designconcurrencymemory-managementcompilers

Last 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 write 5 DOUBLE instead of 5 5 +

When a shortcut is invoked, arguments are popped from the evaluation stack and substituted into the definition.

Your tasks:

  1. Choose a data structure for storing shortcuts with efficient lookup
  2. Describe your evaluation algorithm
  3. 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) -> bool and pop(T& out) -> bool methods
  • 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:

  1. Identify which variables are at risk
  2. Show how to use alignment directives to place them on separate cache lines
  3. 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/free overhead

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