Design a C++ Ring Buffer for Producer-Consumer Use
Company: Applied
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Technical Screen
Design and, where useful, sketch the C++ implementation of a fixed-capacity ring buffer used between producers and consumers. The initial request does not specify overflow behavior, whether calls block, or how many producer and consumer threads exist. Begin by clarifying those choices, then present one correct design for the contract you select and explain how the design changes for other contracts.
### Constraints & Assumptions
- Storage capacity is fixed after construction and slots are reused as indices wrap.
- The design must distinguish full from empty and preserve FIFO order.
- State whether the stored type is trivially copyable or requires explicit object construction and destruction.
- State whether the chosen contract is single-producer/single-consumer, multi-producer/multi-consumer, blocking, non-blocking, or lock-free; do not silently combine incompatible guarantees.
### Clarifying Questions to Ask
- Should a producer block, reject, or overwrite when the buffer is full?
- Should a consumer block or return an empty result when no item is available?
- How many producer and consumer threads are there, and is lock-freedom required?
- How are shutdown, cancellation, exceptions, and object ownership handled?
### What a Strong Answer Covers
- A precise API and state invariant for read position, write position, and occupancy or generation state.
- Correct wraparound and a reliable way to distinguish full from empty.
- For an SPSC design, atomic publication with justified acquire/release ordering and no concurrent access to an unpublished slot.
- For a blocking or MPMC design, a mutex and condition-variable predicate that handles spurious wakeups and shutdown.
- Safe construction, move, destruction, and cache-sharing considerations for C++ objects.
- Tests for wraparound, full and empty transitions, concurrency, shutdown, and long-running index behavior.
### Follow-up Questions
- What changes if overwriting the oldest item is required?
- Why is a design correct for SPSC but unsafe for multiple producers?
- How would you expose backpressure and observe sustained saturation?
Overview: Design a fixed-capacity C++ ring buffer for producer-consumer use after making overflow, blocking, and concurrency semantics explicit. Explain FIFO wraparound, full-versus-empty state, object lifetime, synchronization, memory ordering, and how the design changes across thread models.