bounded_threadsafe_queue.h 5.5 KB

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