libxr  1.0
Want to be the best embedded framework
Loading...
Searching...
No Matches
lockfree_queue.hpp
1#pragma once
2
3#include <atomic>
4#include <cstddef>
5#include <cstdint>
6#include <type_traits>
7
8#include "libxr_def.hpp"
9#include "libxr_mem.hpp"
10
11namespace LibXR
12{
13
28template <typename Data>
29class alignas(LibXR::CACHE_LINE_SIZE) LockFreeQueue
30{
31 inline constexpr size_t AlignUp(size_t size, size_t align)
32 {
33 return (size / align + 1) * align;
34 }
35
36 public:
47 LockFreeQueue(size_t length)
48 : head_(0),
49 tail_(0),
50 LENGTH(AlignUp(length, LibXR::ALIGN_SIZE) - 1),
51 queue_handle_(new Data[LENGTH + 1])
52 {
53 }
54
61 ~LockFreeQueue() { delete[] queue_handle_; }
62
68 Data* operator[](uint32_t index) { return &queue_handle_[static_cast<size_t>(index)]; }
69
77 template <typename ElementData = Data>
78 ErrorCode Push(ElementData&& item)
79 {
80 const auto CURRENT_TAIL = tail_.load(std::memory_order_relaxed);
81 const auto NEXT_TAIL = Increment(CURRENT_TAIL);
82
83 if (NEXT_TAIL == head_.load(std::memory_order_acquire))
84 {
85 return ErrorCode::FULL;
86 }
87
88 queue_handle_[CURRENT_TAIL] = std::forward<ElementData>(item);
89 tail_.store(NEXT_TAIL, std::memory_order_release);
90 return ErrorCode::OK;
91 }
92
100 template <typename ElementData = Data>
101 ErrorCode Pop(ElementData& item)
102 {
103 auto current_head = head_.load(std::memory_order_relaxed);
104
105 while (true)
106 {
107 if (current_head == tail_.load(std::memory_order_acquire))
108 {
109 return ErrorCode::EMPTY;
110 }
111
112 item = queue_handle_[current_head];
113
114 if (head_.compare_exchange_weak(current_head, Increment(current_head),
115 std::memory_order_acq_rel,
116 std::memory_order_relaxed))
117 {
118 return ErrorCode::OK;
119 }
120 }
121 }
122
141 ErrorCode Pop(Data& item)
142 {
143 auto current_head = head_.load(std::memory_order_relaxed);
144
145 while (true)
146 {
147 if (current_head == tail_.load(std::memory_order_acquire))
148 {
149 return ErrorCode::EMPTY;
150 }
151
152 item = queue_handle_[current_head];
153
154 if (head_.compare_exchange_weak(current_head, Increment(current_head),
155 std::memory_order_acq_rel,
156 std::memory_order_relaxed))
157 {
158 return ErrorCode::OK;
159 }
160 }
161 }
162
171 {
172 auto current_head = head_.load(std::memory_order_relaxed);
173
174 while (true)
175 {
176 if (current_head == tail_.load(std::memory_order_acquire))
177 {
178 return ErrorCode::EMPTY;
179 }
180
181 if (head_.compare_exchange_weak(current_head, Increment(current_head),
182 std::memory_order_acq_rel,
183 std::memory_order_relaxed))
184 {
185 return ErrorCode::OK;
186 }
187 }
188 }
189
198 ErrorCode Peek(Data& item)
199 {
200 while (true)
201 {
202 auto current_head = head_.load(std::memory_order_relaxed);
203 if (current_head == tail_.load(std::memory_order_acquire))
204 {
205 return ErrorCode::EMPTY;
206 }
207
208 item = queue_handle_[current_head];
209
210 if (head_.load(std::memory_order_acquire) == current_head)
211 {
212 return ErrorCode::OK;
213 }
214 }
215 }
216
225 ErrorCode PushBatch(const Data* data, size_t size)
226 {
227 auto current_tail = tail_.load(std::memory_order_relaxed);
228 auto current_head = head_.load(std::memory_order_acquire);
229
230 size_t capacity = LENGTH + 1;
231 size_t free_space = (current_tail >= current_head)
232 ? (capacity - (current_tail - current_head) - 1)
233 : (current_head - current_tail - 1);
234
235 if (free_space < size)
236 {
237 return ErrorCode::FULL;
238 }
239
240 size_t first_chunk = LibXR::min(size, capacity - current_tail);
241 LibXR::Memory::FastCopy(reinterpret_cast<void*>(queue_handle_ + current_tail),
242 reinterpret_cast<const void*>(data),
243 first_chunk * sizeof(Data));
244
245 if (size > first_chunk)
246 {
247 LibXR::Memory::FastCopy(reinterpret_cast<void*>(queue_handle_),
248 reinterpret_cast<const void*>(data + first_chunk),
249 (size - first_chunk) * sizeof(Data));
250 }
251
252 tail_.store((current_tail + size) % capacity, std::memory_order_release);
253 return ErrorCode::OK;
254 }
255
268 template <typename Writer>
269 ErrorCode PushWithWriter(size_t size, Writer&& writer)
270 {
271 static_assert(std::is_invocable_v<Writer&, Data*, size_t>,
272 "PushWithWriter writer must be callable as "
273 "ErrorCode(Data* buffer, size_t chunk_size)");
274 using WriterRet = std::invoke_result_t<Writer&, Data*, size_t>;
275 static_assert(std::is_convertible_v<WriterRet, ErrorCode>,
276 "PushWithWriter writer return type must be convertible to ErrorCode");
277
278 if (size == 0U)
279 {
280 return ErrorCode::OK;
281 }
282
283 const auto current_tail = tail_.load(std::memory_order_relaxed);
284 const auto current_head = head_.load(std::memory_order_acquire);
285 const size_t capacity = LENGTH + 1;
286 const size_t free_space =
287 (current_tail >= current_head) ? (capacity - (current_tail - current_head) - 1)
288 : (current_head - current_tail - 1);
289
290 if (free_space < size)
291 {
292 return ErrorCode::FULL;
293 }
294
295 const size_t first_chunk = LibXR::min(size, capacity - static_cast<size_t>(current_tail));
296 Writer& writer_ref = writer;
297 const ErrorCode first_ec = writer_ref(queue_handle_ + current_tail, first_chunk);
298 if (first_ec != ErrorCode::OK)
299 {
300 return first_ec;
301 }
302
303 if (size > first_chunk)
304 {
305 const ErrorCode second_ec = writer_ref(queue_handle_, size - first_chunk);
306 if (second_ec != ErrorCode::OK)
307 {
308 return second_ec;
309 }
310 }
311
312 tail_.store((current_tail + size) % capacity, std::memory_order_release);
313 return ErrorCode::OK;
314 }
315
328 template <typename Reader>
329 ErrorCode PopWithReader(size_t size, Reader&& reader)
330 {
331 static_assert(std::is_invocable_v<Reader&, const Data*, size_t>,
332 "PopWithReader reader must be callable as "
333 "ErrorCode(const Data* buffer, size_t chunk_size)");
334 using ReaderRet = std::invoke_result_t<Reader&, const Data*, size_t>;
335 static_assert(std::is_convertible_v<ReaderRet, ErrorCode>,
336 "PopWithReader reader return type must be convertible to ErrorCode");
337
338 if (size == 0U)
339 {
340 return ErrorCode::OK;
341 }
342
343 const auto current_head = head_.load(std::memory_order_relaxed);
344 const auto current_tail = tail_.load(std::memory_order_acquire);
345 const size_t capacity = LENGTH + 1;
346 const size_t available = (current_tail >= current_head)
347 ? (current_tail - current_head)
348 : (capacity - current_head + current_tail);
349
350 if (available < size)
351 {
352 return ErrorCode::EMPTY;
353 }
354
355 const size_t first_chunk = LibXR::min(size, capacity - static_cast<size_t>(current_head));
356 Reader& reader_ref = reader;
357 const ErrorCode first_ec = reader_ref(queue_handle_ + current_head, first_chunk);
358 if (first_ec != ErrorCode::OK)
359 {
360 return first_ec;
361 }
362
363 if (size > first_chunk)
364 {
365 const ErrorCode second_ec = reader_ref(queue_handle_, size - first_chunk);
366 if (second_ec != ErrorCode::OK)
367 {
368 return second_ec;
369 }
370 }
371
372 head_.store((current_head + size) % capacity, std::memory_order_release);
373 return ErrorCode::OK;
374 }
383 ErrorCode PopBatch(Data* data, size_t size)
384 {
385 size_t capacity = LENGTH + 1;
386
387 while (true)
388 {
389 auto current_head = head_.load(std::memory_order_relaxed);
390 auto current_tail = tail_.load(std::memory_order_acquire);
391
392 size_t available = (current_tail >= current_head)
393 ? (current_tail - current_head)
394 : (capacity - current_head + current_tail);
395
396 if (available < size)
397 {
398 return ErrorCode::EMPTY;
399 }
400
401 if (data != nullptr)
402 {
403 size_t first_chunk = LibXR::min(size, capacity - current_head);
405 reinterpret_cast<void*>(data),
406 reinterpret_cast<const void*>(queue_handle_ + current_head),
407 first_chunk * sizeof(Data));
408
409 if (size > first_chunk)
410 {
411 LibXR::Memory::FastCopy(reinterpret_cast<void*>(data + first_chunk),
412 reinterpret_cast<const void*>(queue_handle_),
413 (size - first_chunk) * sizeof(Data));
414 }
415 }
416
417 size_t new_head = (current_head + size) % capacity;
418
419 if (head_.compare_exchange_weak(current_head, new_head, std::memory_order_acq_rel,
420 std::memory_order_relaxed))
421 {
422 return ErrorCode::OK;
423 }
424 }
425 }
426
436 ErrorCode PeekBatch(Data* data, size_t size)
437 {
438 if (size == 0)
439 {
440 return ErrorCode::OK;
441 }
442
443 const size_t CAPACITY = LENGTH + 1;
444
445 while (true)
446 {
447 auto current_head = head_.load(std::memory_order_relaxed);
448 auto current_tail = tail_.load(std::memory_order_acquire);
449
450 size_t available = (current_tail >= current_head)
451 ? (current_tail - current_head)
452 : (CAPACITY - current_head + current_tail);
453
454 if (available < size)
455 {
456 return ErrorCode::EMPTY;
457 }
458
459 if (data != nullptr)
460 {
461 size_t first_chunk = LibXR::min(size, CAPACITY - current_head);
463 reinterpret_cast<void*>(data),
464 reinterpret_cast<const void*>(queue_handle_ + current_head),
465 first_chunk * sizeof(Data));
466
467 if (size > first_chunk)
468 {
469 LibXR::Memory::FastCopy(reinterpret_cast<void*>(data + first_chunk),
470 reinterpret_cast<const void*>(queue_handle_),
471 (size - first_chunk) * sizeof(Data));
472 }
473 }
474
475 if (head_.load(std::memory_order_acquire) == current_head)
476 {
477 return ErrorCode::OK;
478 }
479 }
480 }
481
488 void Reset()
489 {
490 head_.store(0, std::memory_order_relaxed);
491 tail_.store(0, std::memory_order_relaxed);
492 }
493
498 size_t Size() const
499 {
500 const auto CURRENT_HEAD = head_.load(std::memory_order_acquire);
501 const auto CURRENT_TAIL = tail_.load(std::memory_order_acquire);
502 return (CURRENT_TAIL >= CURRENT_HEAD) ? (CURRENT_TAIL - CURRENT_HEAD)
503 : ((LENGTH + 1) - CURRENT_HEAD + CURRENT_TAIL);
504 }
505
509 size_t EmptySize() { return LENGTH - Size(); }
510
514 size_t MaxSize() const { return LENGTH; }
515
516 private:
517 alignas(LibXR::CACHE_LINE_SIZE) std::atomic<uint32_t> head_;
518 alignas(LibXR::CACHE_LINE_SIZE) std::atomic<uint32_t> tail_;
519 const size_t LENGTH;
520 Data* queue_handle_;
521
522 uint32_t Increment(uint32_t index) const { return (index + 1) % (LENGTH + 1); }
523};
524
525} // namespace LibXR
无锁队列实现 / Lock-free queue implementation
void Reset()
重置队列 / Resets the queue
size_t MaxSize() const
获取队列的最大容量 / Returns the maximum capacity of the queue
ErrorCode Pop(ElementData &item)
从队列中弹出数据 / Pops data from the queue
ErrorCode Pop()
从队列中弹出数据(不返回数据) / Pops data from the queue (without returning data)
ErrorCode PushBatch(const Data *data, size_t size)
批量推入数据 / Pushes multiple elements into the queue
ErrorCode Push(ElementData &&item)
向队列中推入数据 / Pushes data into the queue
ErrorCode Pop(Data &item)
从队列中移除头部元素,并获取该元素的数据 (Remove the front element from the queue and retrieve its data).
size_t EmptySize()
计算队列剩余可用空间 / Calculates the remaining available space in the queue
ErrorCode PushWithWriter(size_t size, Writer &&writer)
通过写入器回调写入固定长度数据(单生产者) / Push fixed-size data via writer callback (single producer)
LockFreeQueue(size_t length)
构造函数 / Constructor
ErrorCode PopWithReader(size_t size, Reader &&reader)
通过读取器回调弹出固定长度数据(单消费者) / Pop fixed-size data via reader callback (single consumer)
ErrorCode PeekBatch(Data *data, size_t size)
批量查看队列中的数据(不移除) / Peeks multiple elements from the queue without removing them
Data * operator[](uint32_t index)
获取指定索引的数据指针 / Retrieves the data pointer at a specified index
size_t Size() const
获取当前队列中的元素数量 / Returns the number of elements currently in the queue
~LockFreeQueue()
析构函数 / Destructor
ErrorCode PopBatch(Data *data, size_t size)
批量弹出数据 / Pops multiple elements from the queue
ErrorCode Peek(Data &item)
获取队列头部数据但不弹出 / Retrieves the front data of the queue without popping
static void FastCopy(void *dst, const void *src, size_t size)
快速内存拷贝 / Fast memory copy
Definition libxr_mem.cpp:5
LibXR 命名空间
Definition ch32_can.hpp:14
ErrorCode
定义错误码枚举
@ EMPTY
为空 | Empty
@ FULL
已满 | Full
@ OK
操作成功 | Operation successful
constexpr auto min(LeftType a, RightType b) -> std::common_type_t< LeftType, RightType >
计算两个数的最小值
constexpr size_t CACHE_LINE_SIZE
缓存行大小 / Cache line size
Definition libxr_def.hpp:32
constexpr size_t ALIGN_SIZE
平台自然对齐大小 / Native platform alignment size
Definition libxr_def.hpp:35