#ifndef RING_BUFFER_H #define RING_BUFFER_H #include #include #include template class RingBuffer { public: RingBuffer(unsigned int size) : read_index(0), write_index(0), filled(0), buf(size) { } void write(T item) { std::unique_lock lock(mutex); while (filled == buf.capacity()) { ready_for_writing.wait(lock); } buf[write_index] = item; write_index = (write_index + 1) % buf.capacity(); ++filled; ready_for_reading.notify_one(); } void read(T& item) { std::unique_lock lock(mutex); while (filled == 0) { ready_for_reading.wait(lock); } item = buf[read_index]; read_index = (read_index + 1) % buf.capacity(); --filled; ready_for_writing.notify_one(); } private: unsigned int read_index; unsigned int write_index; unsigned int filled; std::vector buf; std::mutex mutex; std::condition_variable ready_for_reading; std::condition_variable ready_for_writing; }; #endif