bounded_threadsafe_queue.h 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. // SPDX-FileCopyrightText: Copyright (c) 2020 Erik Rigtorp <erik@rigtorp.se>
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. #include <atomic>
  5. #include <bit>
  6. #include <condition_variable>
  7. #include <memory>
  8. #include <mutex>
  9. #include <new>
  10. #include <stop_token>
  11. #include <type_traits>
  12. #include <utility>
  13. namespace Common {
  14. #if defined(__cpp_lib_hardware_interference_size)
  15. constexpr size_t hardware_interference_size = std::hardware_destructive_interference_size;
  16. #else
  17. constexpr size_t hardware_interference_size = 64;
  18. #endif
  19. template <typename T, size_t capacity = 0x400>
  20. class MPSCQueue {
  21. public:
  22. explicit MPSCQueue() : allocator{std::allocator<Slot<T>>()} {
  23. // Allocate one extra slot to prevent false sharing on the last slot
  24. slots = allocator.allocate(capacity + 1);
  25. // Allocators are not required to honor alignment for over-aligned types
  26. // (see http://eel.is/c++draft/allocator.requirements#10) so we verify
  27. // alignment here
  28. if (reinterpret_cast<uintptr_t>(slots) % alignof(Slot<T>) != 0) {
  29. allocator.deallocate(slots, capacity + 1);
  30. throw std::bad_alloc();
  31. }
  32. for (size_t i = 0; i < capacity; ++i) {
  33. std::construct_at(&slots[i]);
  34. }
  35. static_assert(std::has_single_bit(capacity), "capacity must be an integer power of 2");
  36. static_assert(alignof(Slot<T>) == hardware_interference_size,
  37. "Slot must be aligned to cache line boundary to prevent false sharing");
  38. static_assert(sizeof(Slot<T>) % hardware_interference_size == 0,
  39. "Slot size must be a multiple of cache line size to prevent "
  40. "false sharing between adjacent slots");
  41. static_assert(sizeof(MPSCQueue) % hardware_interference_size == 0,
  42. "Queue size must be a multiple of cache line size to "
  43. "prevent false sharing between adjacent queues");
  44. }
  45. ~MPSCQueue() noexcept {
  46. for (size_t i = 0; i < capacity; ++i) {
  47. std::destroy_at(&slots[i]);
  48. }
  49. allocator.deallocate(slots, capacity + 1);
  50. }
  51. // The queue must be both non-copyable and non-movable
  52. MPSCQueue(const MPSCQueue&) = delete;
  53. MPSCQueue& operator=(const MPSCQueue&) = delete;
  54. MPSCQueue(MPSCQueue&&) = delete;
  55. MPSCQueue& operator=(MPSCQueue&&) = delete;
  56. void Push(const T& v) noexcept {
  57. static_assert(std::is_nothrow_copy_constructible_v<T>,
  58. "T must be nothrow copy constructible");
  59. emplace(v);
  60. }
  61. template <typename P, typename = std::enable_if_t<std::is_nothrow_constructible_v<T, P&&>>>
  62. void Push(P&& v) noexcept {
  63. emplace(std::forward<P>(v));
  64. }
  65. void Pop(T& v, std::stop_token stop) noexcept {
  66. auto const tail = tail_.fetch_add(1);
  67. auto& slot = slots[idx(tail)];
  68. if (!slot.turn.test()) {
  69. std::unique_lock lock{cv_mutex};
  70. cv.wait(lock, stop, [&slot] { return slot.turn.test(); });
  71. }
  72. v = slot.move();
  73. slot.destroy();
  74. slot.turn.clear();
  75. slot.turn.notify_one();
  76. }
  77. private:
  78. template <typename U = T>
  79. struct Slot {
  80. ~Slot() noexcept {
  81. if (turn.test()) {
  82. destroy();
  83. }
  84. }
  85. template <typename... Args>
  86. void construct(Args&&... args) noexcept {
  87. static_assert(std::is_nothrow_constructible_v<U, Args&&...>,
  88. "T must be nothrow constructible with Args&&...");
  89. std::construct_at(reinterpret_cast<U*>(&storage), std::forward<Args>(args)...);
  90. }
  91. void destroy() noexcept {
  92. static_assert(std::is_nothrow_destructible_v<U>, "T must be nothrow destructible");
  93. std::destroy_at(reinterpret_cast<U*>(&storage));
  94. }
  95. U&& move() noexcept {
  96. return reinterpret_cast<U&&>(storage);
  97. }
  98. // Align to avoid false sharing between adjacent slots
  99. alignas(hardware_interference_size) std::atomic_flag turn{};
  100. struct aligned_store {
  101. struct type {
  102. alignas(U) unsigned char data[sizeof(U)];
  103. };
  104. };
  105. typename aligned_store::type storage;
  106. };
  107. template <typename... Args>
  108. void emplace(Args&&... args) noexcept {
  109. static_assert(std::is_nothrow_constructible_v<T, Args&&...>,
  110. "T must be nothrow constructible with Args&&...");
  111. auto const head = head_.fetch_add(1);
  112. auto& slot = slots[idx(head)];
  113. slot.turn.wait(true);
  114. slot.construct(std::forward<Args>(args)...);
  115. slot.turn.test_and_set();
  116. cv.notify_one();
  117. }
  118. constexpr size_t idx(size_t i) const noexcept {
  119. return i & mask;
  120. }
  121. static constexpr size_t mask = capacity - 1;
  122. // Align to avoid false sharing between head_ and tail_
  123. alignas(hardware_interference_size) std::atomic<size_t> head_{0};
  124. alignas(hardware_interference_size) std::atomic<size_t> tail_{0};
  125. std::mutex cv_mutex;
  126. std::condition_variable_any cv;
  127. Slot<T>* slots;
  128. [[no_unique_address]] std::allocator<Slot<T>> allocator;
  129. static_assert(std::is_nothrow_copy_assignable_v<T> || std::is_nothrow_move_assignable_v<T>,
  130. "T must be nothrow copy or move assignable");
  131. static_assert(std::is_nothrow_destructible_v<T>, "T must be nothrow destructible");
  132. };
  133. } // namespace Common