Template Class RingBuffer#

Nested Relationships#

Nested Types#

Class Documentation#

template<typename T>
class RingBuffer#

Lock-free Single-Producer / Single-Consumer (SPSC) ring buffer.

Designed for the video pipeline: one VideoGrabber thread pushes frames, one VideoEncoder thread pops them — with zero locks and zero dynamic allocation after construction.

Usage rules

  • push() must only ever be called from one thread (the producer).

  • pop() must only ever be called from one thread (the consumer).

  • The two atomics are on separate cache lines to prevent false sharing.

  • Capacity is rounded up to the next power of two internally.

Example
RingBuffer<std::shared_ptr<VideoFrame>> buf(128);

// Producer thread:
if (!buf.push(frame)) {
    log_warning("Ring buffer full — frame dropped");
}

// Consumer thread:
std::shared_ptr<VideoFrame> f;
while (buf.pop(f)) {
    encode(f);
}

Template Parameters:

T – Element type. Must be default-constructible.

Public Functions

inline explicit RingBuffer(std::size_t capacity = 0)#
Parameters:

capacity – Desired capacity. Rounded up to the next power of two.

inline void reset(std::size_t capacity)#

Resizes and clears the buffer.

Parameters:

capacity – New capacity. Rounded up to the next power of two.

Warning

Not thread-safe — call only when no producer or consumer thread is running.

inline bool push(const T &item) noexcept#

Writes one item (copy).

Called from the producer thread only.

Parameters:

item – Item to enqueue.

Returns:

false if the buffer is full (item is discarded).

inline bool push(T &&item) noexcept#

Writes one item (move).

Called from the producer thread only.

Parameters:

item – Item to move-enqueue.

Returns:

false if the buffer is full (item is discarded).

inline bool pop(T &out) noexcept#

Reads and removes one item.

Called from the consumer thread only.

Parameters:

out – Output reference populated with the dequeued item.

Returns:

false if the buffer is empty.

inline std::size_t available_read() const noexcept#
Returns:

Number of items available for reading.

inline std::size_t available_write() const noexcept#
Returns:

Number of additional items that can be pushed before the buffer is full.

inline std::size_t capacity() const noexcept#
Returns:

The actual capacity (always a power of two).

inline bool empty() const noexcept#
Returns:

true if no items are available for reading.

inline bool full() const noexcept#
Returns:

true if no more items can be pushed without dropping.