bounded_threadsafe_queue.h 5.9 KB

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