1#ifndef OF_TRIPLEBUF_HPP
2#define OF_TRIPLEBUF_HPP
6#include <zephyr/sys/atomic.h>
7#include <zephyr/kernel.h>
11using std::hardware_destructive_interference_size;
16 template <
typename T,
size_t N>
17 requires std::is_standard_layout_v<T> && (N >= 2)
28 void write(
const T& data)
noexcept
30 auto next_slot = (m_next_write_idx + 1) % N;
31 auto& slot = m_slots[next_slot];
32 atomic_inc(&slot.version);
36 atomic_inc(&slot.version);
38 atomic_set(&m_latest_idx, next_slot);
39 m_next_write_idx = next_slot;
42 template <
typename Func>
45 auto next_slot = (m_next_write_idx + 1) % N;
46 auto& slot = m_slots[next_slot];
48 atomic_inc(&slot.version);
52 atomic_inc(&slot.version);
55 atomic_set(&m_latest_idx, next_slot);
56 m_next_write_idx = next_slot;
62 auto& slot = m_slots[atomic_get(&m_latest_idx)];
64 auto v1 = atomic_get(&slot.version);
70 auto v2 = atomic_get(&slot.version);
71 return v1 == v2 ? out_data : std::nullopt;
79 auto& slot = m_slots[atomic_get(&m_latest_idx)];
80 atomic_val_t v1, v2{};
83 v1 = atomic_get(&slot.version);
95 v2 = atomic_get(&slot.version);
103# pragma GCC diagnostic push
104# pragma GCC diagnostic ignored "-Winterference-size"
106 struct alignas (hardware_destructive_interference_size) Slot
108 atomic_t version = ATOMIC_INIT(0);
112# pragma GCC diagnostic pop
115 std::array<Slot, N> m_slots;
117 atomic_t m_latest_idx = ATOMIC_INIT(0);
119 atomic_val_t m_next_write_idx{0};
void write(const T &data) noexcept
定义 NBuf.hpp:28
T read() const noexcept
定义 NBuf.hpp:76
NBuf(NBuf &&other)=delete
void manipulate(const Func &func)
定义 NBuf.hpp:43
NBuf(const NBuf &)=delete
std::optional< T > try_read() const noexcept
定义 NBuf.hpp:59