Data Structures & Algorithms · Interview question

Why can a single-producer/single-consumer ring buffer be lock-free, and what's the catch?

A strong answer

Because each side owns exactly one index: the producer only writes head and only reads tail; the consumer only writes tail and only reads head. There's no variable that both sides write, so there's no read-modify-write race to protect, no lock needed. The catch is ordering: the producer must write the data slot before advancing head (publish the pointer after the payload), or the consumer could observe an advanced head and read a slot that hasn't been filled yet. You also mark head/tail volatile so the compiler actually re-reads them rather than caching across the ISR boundary, and on multi-core or weakly-ordered architectures you need a memory barrier between the data write and the index publish. The lock-free property is specific to one producer and one consumer; add a second producer or consumer and two writers now race on the same index, requiring a critical section or atomics.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

Ring Buffers

The fixed-memory FIFO behind every UART driver: head and tail indices wrapping a static array, O(1) push/pop, and the full-vs-empty trick, plus the lock-free single-producer/consumer pattern.

More Ring Buffers questions

Browse all 472 interview questions
Why can a single-producer/single-consumer ring buffer be lock-free, and what's the catch? | EmbeddedPrep.io