MayaFlux 1.0.0
Digital-First Multimedia Processing Framework
Loading...
Searching...
No Matches
SnapshotCell.hpp
Go to the documentation of this file.
1#pragma once
2
3#include "SweepList.hpp"
4
5namespace MayaFlux::Memory {
6
7/**
8 * @class SnapshotCell
9 * @brief Lock-free cell holding one immutable snapshot of a value, read without blocking.
10 *
11 * read() returns a Guard on the snapshot that was current at that moment. It stays
12 * valid and unchanged while the Guard lives, whatever writers publish meanwhile.
13 * update() copies the current snapshot, edits the copy and swaps it in, retrying
14 * when another writer got there first. publish() and reset() replace it
15 * unconditionally.
16 *
17 * Replaced snapshots are freed by a later writer once no Guard is held, so a Guard
18 * kept for long delays freeing. Hold a Guard for the lookup only, and never past
19 * the cell's lifetime.
20 *
21 * Suited to values read often and replaced rarely, since every update copies the
22 * whole value.
23 *
24 * @tparam T Snapshot type. Readers see it as const, so it needs no internal
25 * synchronisation. update() needs it default constructible and copyable.
26 *
27 * @code{.cpp}
28 * Memory::SnapshotCell<std::unordered_map<int, float>> table;
29 *
30 * table.update([](auto& map) { map[7] = 0.5F; });
31 *
32 * if (auto view = table.read()) {
33 * auto it = view->find(7);
34 * }
35 * @endcode
36 */
37template <typename T>
39public:
40 /**
41 * @class Guard
42 * @brief Keeps one snapshot alive and unchanged while it exists.
43 *
44 * Empty when the cell held nothing at read(). Movable, not copyable.
45 */
46 class Guard {
47 public:
48 Guard() noexcept = default;
49
50 ~Guard() { release(); }
51
52 Guard(const Guard&) = delete;
53 Guard& operator=(const Guard&) = delete;
54
55 Guard(Guard&& other) noexcept
56 : m_cell(std::exchange(other.m_cell, nullptr))
57 , m_value(std::exchange(other.m_value, nullptr))
58 {
59 }
60
61 Guard& operator=(Guard&& other) noexcept
62 {
63 if (this != &other) {
64 release();
65 m_cell = std::exchange(other.m_cell, nullptr);
66 m_value = std::exchange(other.m_value, nullptr);
67 }
68 return *this;
69 }
70
71 /** @brief The snapshot, or null when the cell was empty. */
72 [[nodiscard]] const T* get() const noexcept { return m_value; }
73
74 [[nodiscard]] const T* operator->() const noexcept { return m_value; }
75
76 [[nodiscard]] const T& operator*() const noexcept { return *m_value; }
77
78 [[nodiscard]] explicit operator bool() const noexcept { return m_value != nullptr; }
79
80 private:
81 friend class SnapshotCell;
82
83 Guard(const SnapshotCell* cell, const T* value) noexcept
84 : m_cell(cell)
85 , m_value(value)
86 {
87 }
88
89 void release() noexcept
90 {
91 if (m_cell) {
92 m_cell->m_readers.fetch_sub(1);
93 }
94 m_cell = nullptr;
95 m_value = nullptr;
96 }
97
98 const SnapshotCell* m_cell { nullptr };
99 const T* m_value { nullptr };
100 };
101
102 /** @brief Creates an empty cell. */
103 SnapshotCell() noexcept = default;
104
105 /** @brief Creates a cell already holding @p initial. */
106 explicit SnapshotCell(T initial)
107 : m_head(std::make_unique<T>(std::move(initial)).release())
108 {
109 }
110
111 SnapshotCell(const SnapshotCell&) = delete;
115
116 /**
117 * @brief Frees the current snapshot and every retired one.
118 *
119 * No Guard may be alive and no other thread may be inside the cell.
120 */
122 {
123 delete m_head.load();
124 }
125
126 /**
127 * @brief Pins the current snapshot.
128 * @return A Guard over it, empty when the cell holds nothing.
129 */
130 [[nodiscard]] Guard read() const noexcept
131 {
132 m_readers.fetch_add(1);
133 const T* value = m_head.load();
134 if (!value) {
135 m_readers.fetch_sub(1);
136 return {};
137 }
138 return Guard(this, value);
139 }
140
141 /**
142 * @brief Replaces the snapshot with @p value, whatever it was.
143 *
144 * Concurrent publishes are ordered arbitrarily and the last one wins. Use
145 * update() when the new value depends on the old one.
146 */
147 void publish(T value)
148 {
149 replace(std::make_unique<T>(std::move(value)).release());
150 }
151
152 /** @brief Empties the cell. */
153 void reset()
154 {
155 replace(nullptr);
156 }
157
158 /**
159 * @brief Edits a copy of the current snapshot and publishes it.
160 *
161 * Starts from a default constructed T when the cell is empty. If another
162 * writer publishes first, the copy is discarded and @p edit runs again on
163 * the newer snapshot, so it may run more than once and must depend only on
164 * the value it is given.
165 *
166 * @tparam Edit Callable (T&) returning void, or bool.
167 * @param edit Mutates the copy. A bool return of false abandons the edit
168 * and publishes nothing.
169 * @return true if a new snapshot was published, false if @p edit declined.
170 */
171 template <typename Edit>
172 requires std::invocable<Edit&, T&> && std::default_initializable<T> && std::copy_constructible<T>
173 bool update(Edit edit)
174 {
175 using Result = std::invoke_result_t<Edit&, T&>;
176 static_assert(std::is_void_v<Result> || std::is_same_v<Result, bool>,
177 "SnapshotCell::update edit must return void or bool");
178
179 for (;;) {
180 Guard pin = read();
181 const T* current = pin.get();
182
183 auto draft = current ? std::make_unique<T>(*current) : std::make_unique<T>();
184
185 if constexpr (std::is_void_v<Result>) {
186 std::invoke(edit, *draft);
187 } else if (!std::invoke(edit, *draft)) {
188 return false;
189 }
190
191 const T* expected = current;
192 if (m_head.compare_exchange_strong(expected, draft.get())) {
193 draft.release();
194 pin = Guard {};
195 retire(current);
196 return true;
197 }
198 }
199 }
200
201private:
202 void replace(const T* next)
203 {
204 retire(m_head.exchange(next));
205 }
206
207 void retire(const T* old)
208 {
209 if (old) {
210 m_retired.push(std::unique_ptr<const T>(old));
211 }
212 reclaim();
213 }
214
215 void reclaim()
216 {
217 if (m_retired.empty()) {
218 return;
219 }
220 m_retired.sweep(
221 [this](std::unique_ptr<const T>&) { return m_readers.load() == 0; },
222 [](std::unique_ptr<const T>& snapshot) { snapshot.reset(); });
223 }
224
225 alignas(64) std::atomic<const T*> m_head { nullptr };
226 alignas(64) mutable std::atomic<uint32_t> m_readers { 0 };
228};
229
230} // namespace MayaFlux::Memory
const T * get() const noexcept
The snapshot, or null when the cell was empty.
Guard & operator=(const Guard &)=delete
Guard(const SnapshotCell *cell, const T *value) noexcept
const T * operator->() const noexcept
const T & operator*() const noexcept
Guard & operator=(Guard &&other) noexcept
Keeps one snapshot alive and unchanged while it exists.
SnapshotCell(const SnapshotCell &)=delete
SweepList< std::unique_ptr< const T > > m_retired
Guard read() const noexcept
Pins the current snapshot.
void publish(T value)
Replaces the snapshot with value, whatever it was.
std::atomic< uint32_t > m_readers
~SnapshotCell()
Frees the current snapshot and every retired one.
std::atomic< const T * > m_head
SnapshotCell & operator=(const SnapshotCell &)=delete
SnapshotCell() noexcept=default
Creates an empty cell.
void reset()
Empties the cell.
SnapshotCell & operator=(SnapshotCell &&)=delete
SnapshotCell(SnapshotCell &&)=delete
bool update(Edit edit)
Edits a copy of the current snapshot and publishes it.
Lock-free, unbounded, multi-producer collection of in-flight items.
Definition SweepList.hpp:33