2025-06-03 00:50:08 +02:00
|
|
|
#pragma once
|
2025-06-03 01:25:44 +02:00
|
|
|
#include <array>
|
2025-06-03 00:50:08 +02:00
|
|
|
#include <mutex>
|
|
|
|
|
#include <condition_variable>
|
|
|
|
|
|
|
|
|
|
template <size_t N>
|
|
|
|
|
class RingBuffer {
|
2025-06-03 01:25:44 +02:00
|
|
|
std::array<int, N> data;
|
|
|
|
|
size_t read = 0;
|
|
|
|
|
size_t write = 0;
|
|
|
|
|
bool full = false;
|
|
|
|
|
std::mutex mtx;
|
|
|
|
|
std::condition_variable cv;
|
2025-06-03 00:50:08 +02:00
|
|
|
|
|
|
|
|
public:
|
|
|
|
|
void push(int value) {
|
2025-06-03 01:25:44 +02:00
|
|
|
std::lock_guard<std::mutex> lock(mtx);
|
|
|
|
|
data[write] = value;
|
|
|
|
|
write = (write + 1) % N;
|
|
|
|
|
if (full) read = (read + 1) % N;
|
|
|
|
|
full = (write == read);
|
|
|
|
|
cv.notify_one();
|
2025-06-03 00:50:08 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
int pop() {
|
|
|
|
|
std::unique_lock<std::mutex> lock(mtx);
|
2025-06-03 01:25:44 +02:00
|
|
|
cv.wait(lock, [this]{ return full || write != read; });
|
|
|
|
|
int val = data[read];
|
|
|
|
|
read = (read + 1) % N;
|
2025-06-03 00:50:08 +02:00
|
|
|
full = false;
|
2025-06-03 01:25:44 +02:00
|
|
|
return val;
|
2025-06-03 00:50:08 +02:00
|
|
|
}
|
2025-06-03 01:25:44 +02:00
|
|
|
};
|