stm32rcos
読み取り中…
検索中…
一致する文字列を見つけられません
ring_buffer.hpp
[詳解]
1#pragma once
2
3#include <array>
4#include <atomic>
5#include <cstddef>
6#include <optional>
7
8template <class T, size_t N> class RingBuffer {
9public:
10 bool push(const T &value) {
11 size_t write_idx = write_idx_.load(std::memory_order_relaxed);
12 size_t next_idx = (write_idx + 1) % buf_.size();
13 if (next_idx == read_idx_.load(std::memory_order_acquire)) {
14 return false;
15 }
16 buf_[write_idx] = value;
17 write_idx_.store(next_idx, std::memory_order_release);
18 return true;
19 }
20
21 std::optional<T> pop() {
22 size_t write_idx = write_idx_.load(std::memory_order_acquire);
23 size_t read_idx = read_idx_.load(std::memory_order_relaxed);
24 if (write_idx == read_idx) {
25 return std::nullopt;
26 }
27 std::optional<T> value = buf_[read_idx];
28 size_t next_idx = (read_idx + 1) % buf_.size();
29 read_idx_.store(next_idx, std::memory_order_release);
30 return value;
31 }
32
33 void clear() {
34 write_idx_.store(0, std::memory_order_relaxed);
35 read_idx_.store(0, std::memory_order_release);
36 }
37
38 size_t size() const {
39 size_t write_idx = write_idx_.load(std::memory_order_acquire);
40 size_t read_idx = read_idx_.load(std::memory_order_relaxed);
41 return (write_idx + buf_.size() - read_idx) % buf_.size();
42 }
43
44 constexpr size_t capacity() const { return N; }
45
46private:
47 std::array<T, N + 1> buf_;
48 std::atomic<size_t> write_idx_{0};
49 std::atomic<size_t> read_idx_{0};
50};
Definition ring_buffer.hpp:8
std::optional< T > pop()
Definition ring_buffer.hpp:21
constexpr size_t capacity() const
Definition ring_buffer.hpp:44
size_t size() const
Definition ring_buffer.hpp:38
bool push(const T &value)
Definition ring_buffer.hpp:10
void clear()
Definition ring_buffer.hpp:33