bounded_threadsafe_queue: Use simplified impl of bounded queue

Provides a simplified SPSC, MPSC, and MPMC bounded queue implementation using mutexes.
pull/8/head
Morph 2 years ago
parent 3d4c113037
commit 306840a580

@ -1,159 +1,246 @@
// SPDX-FileCopyrightText: Copyright (c) 2020 Erik Rigtorp <erik@rigtorp.se> // SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: GPL-2.0-or-later
#pragma once #pragma once
#include <atomic> #include <atomic>
#include <bit>
#include <condition_variable> #include <condition_variable>
#include <memory> #include <cstddef>
#include <mutex> #include <mutex>
#include <new> #include <new>
#include <type_traits>
#include <utility>
#include "common/polyfill_thread.h" #include "common/polyfill_thread.h"
namespace Common { namespace Common {
#if defined(__cpp_lib_hardware_interference_size) namespace detail {
constexpr size_t hardware_interference_size = std::hardware_destructive_interference_size; constexpr size_t DefaultCapacity = 0x1000;
#else } // namespace detail
constexpr size_t hardware_interference_size = 64;
#endif template <typename T, size_t Capacity = detail::DefaultCapacity>
class SPSCQueue {
static_assert((Capacity & (Capacity - 1)) == 0, "Capacity must be a power of two.");
template <typename T, size_t capacity = 0x400>
class MPSCQueue {
public: public:
explicit MPSCQueue() : allocator{std::allocator<Slot<T>>()} { void Push(T&& t) {
// Allocate one extra slot to prevent false sharing on the last slot const size_t write_index = m_write_index.load();
slots = allocator.allocate(capacity + 1);
// Allocators are not required to honor alignment for over-aligned types // Wait until we have free slots to write to.
// (see http://eel.is/c++draft/allocator.requirements#10) so we verify while ((write_index - m_read_index.load()) == Capacity) {
// alignment here std::this_thread::yield();
if (reinterpret_cast<uintptr_t>(slots) % alignof(Slot<T>) != 0) {
allocator.deallocate(slots, capacity + 1);
throw std::bad_alloc();
}
for (size_t i = 0; i < capacity; ++i) {
std::construct_at(&slots[i]);
} }
static_assert(std::has_single_bit(capacity), "capacity must be an integer power of 2");
static_assert(alignof(Slot<T>) == hardware_interference_size, // Determine the position to write to.
"Slot must be aligned to cache line boundary to prevent false sharing"); const size_t pos = write_index % Capacity;
static_assert(sizeof(Slot<T>) % hardware_interference_size == 0,
"Slot size must be a multiple of cache line size to prevent " // Push into the queue.
"false sharing between adjacent slots"); m_data[pos] = std::move(t);
static_assert(sizeof(MPSCQueue) % hardware_interference_size == 0,
"Queue size must be a multiple of cache line size to " // Increment the write index.
"prevent false sharing between adjacent queues"); ++m_write_index;
// Notify the consumer that we have pushed into the queue.
std::scoped_lock lock{cv_mutex};
cv.notify_one();
} }
~MPSCQueue() noexcept { template <typename... Args>
for (size_t i = 0; i < capacity; ++i) { void Push(Args&&... args) {
std::destroy_at(&slots[i]); const size_t write_index = m_write_index.load();
// Wait until we have free slots to write to.
while ((write_index - m_read_index.load()) == Capacity) {
std::this_thread::yield();
} }
allocator.deallocate(slots, capacity + 1);
// Determine the position to write to.
const size_t pos = write_index % Capacity;
// Emplace into the queue.
std::construct_at(std::addressof(m_data[pos]), std::forward<Args>(args)...);
// Increment the write index.
++m_write_index;
// Notify the consumer that we have pushed into the queue.
std::scoped_lock lock{cv_mutex};
cv.notify_one();
} }
// The queue must be both non-copyable and non-movable bool TryPop(T& t) {
MPSCQueue(const MPSCQueue&) = delete; return Pop(t);
MPSCQueue& operator=(const MPSCQueue&) = delete; }
MPSCQueue(MPSCQueue&&) = delete; void PopWait(T& t, std::stop_token stop_token) {
MPSCQueue& operator=(MPSCQueue&&) = delete; Wait(stop_token);
Pop(t);
}
void Push(const T& v) noexcept { T PopWait(std::stop_token stop_token) {
static_assert(std::is_nothrow_copy_constructible_v<T>, Wait(stop_token);
"T must be nothrow copy constructible"); T t;
emplace(v); Pop(t);
return t;
} }
template <typename P, typename = std::enable_if_t<std::is_nothrow_constructible_v<T, P&&>>> void Clear() {
void Push(P&& v) noexcept { while (!Empty()) {
emplace(std::forward<P>(v)); Pop();
}
} }
void Pop(T& v, std::stop_token stop) noexcept { bool Empty() const {
auto const tail = tail_.fetch_add(1); return m_read_index.load() == m_write_index.load();
auto& slot = slots[idx(tail)];
if (!slot.turn.test()) {
std::unique_lock lock{cv_mutex};
Common::CondvarWait(cv, lock, stop, [&slot] { return slot.turn.test(); });
} }
v = slot.move();
slot.destroy(); size_t Size() const {
slot.turn.clear(); return m_write_index.load() - m_read_index.load();
slot.turn.notify_one();
} }
private: private:
template <typename U = T> void Pop() {
struct Slot { const size_t read_index = m_read_index.load();
~Slot() noexcept {
if (turn.test()) { // Check if the queue is empty.
destroy(); if (read_index == m_write_index.load()) {
return;
} }
// Determine the position to read from.
const size_t pos = read_index % Capacity;
// Pop the data off the queue, deleting it.
std::destroy_at(std::addressof(m_data[pos]));
// Increment the read index.
++m_read_index;
} }
template <typename... Args> bool Pop(T& t) {
void construct(Args&&... args) noexcept { const size_t read_index = m_read_index.load();
static_assert(std::is_nothrow_constructible_v<U, Args&&...>,
"T must be nothrow constructible with Args&&..."); // Check if the queue is empty.
std::construct_at(reinterpret_cast<U*>(&storage), std::forward<Args>(args)...); if (read_index == m_write_index.load()) {
return false;
} }
void destroy() noexcept { // Determine the position to read from.
static_assert(std::is_nothrow_destructible_v<U>, "T must be nothrow destructible"); const size_t pos = read_index % Capacity;
std::destroy_at(reinterpret_cast<U*>(&storage));
// Pop the data off the queue, moving it.
t = std::move(m_data[pos]);
// Increment the read index.
++m_read_index;
return true;
} }
U&& move() noexcept { void Wait(std::stop_token stop_token) {
return reinterpret_cast<U&&>(storage); std::unique_lock lock{cv_mutex};
Common::CondvarWait(cv, lock, stop_token, [this] { return !Empty(); });
} }
// Align to avoid false sharing between adjacent slots alignas(128) std::atomic_size_t m_read_index{0};
alignas(hardware_interference_size) std::atomic_flag turn{}; alignas(128) std::atomic_size_t m_write_index{0};
struct aligned_store {
struct type { std::array<T, Capacity> m_data;
alignas(U) unsigned char data[sizeof(U)];
}; std::condition_variable_any cv;
std::mutex cv_mutex;
}; };
typename aligned_store::type storage;
template <typename T, size_t Capacity = detail::DefaultCapacity>
class MPSCQueue {
public:
void Push(T&& t) {
std::scoped_lock lock{write_mutex};
spsc_queue.Push(std::move(t));
}
template <typename... Args>
void Push(Args&&... args) {
std::scoped_lock lock{write_mutex};
spsc_queue.Push(std::forward<Args>(args)...);
}
bool TryPop(T& t) {
return spsc_queue.TryPop(t);
}
void PopWait(T& t, std::stop_token stop_token) {
spsc_queue.PopWait(t, stop_token);
}
T PopWait(std::stop_token stop_token) {
return spsc_queue.PopWait(stop_token);
}
void Clear() {
spsc_queue.Clear();
}
bool Empty() {
return spsc_queue.Empty();
}
size_t Size() {
return spsc_queue.Size();
}
private:
SPSCQueue<T, Capacity> spsc_queue;
std::mutex write_mutex;
}; };
template <typename T, size_t Capacity = detail::DefaultCapacity>
class MPMCQueue {
public:
void Push(T&& t) {
std::scoped_lock lock{write_mutex};
spsc_queue.Push(std::move(t));
}
template <typename... Args> template <typename... Args>
void emplace(Args&&... args) noexcept { void Push(Args&&... args) {
static_assert(std::is_nothrow_constructible_v<T, Args&&...>, std::scoped_lock lock{write_mutex};
"T must be nothrow constructible with Args&&..."); spsc_queue.Push(std::forward<Args>(args)...);
auto const head = head_.fetch_add(1);
auto& slot = slots[idx(head)];
slot.turn.wait(true);
slot.construct(std::forward<Args>(args)...);
slot.turn.test_and_set();
cv.notify_one();
} }
constexpr size_t idx(size_t i) const noexcept { bool TryPop(T& t) {
return i & mask; std::scoped_lock lock{read_mutex};
return spsc_queue.TryPop(t);
} }
static constexpr size_t mask = capacity - 1; void PopWait(T& t, std::stop_token stop_token) {
std::scoped_lock lock{read_mutex};
spsc_queue.PopWait(t, stop_token);
}
// Align to avoid false sharing between head_ and tail_ T PopWait(std::stop_token stop_token) {
alignas(hardware_interference_size) std::atomic<size_t> head_{0}; std::scoped_lock lock{read_mutex};
alignas(hardware_interference_size) std::atomic<size_t> tail_{0}; return spsc_queue.PopWait(stop_token);
}
std::mutex cv_mutex; void Clear() {
std::condition_variable_any cv; std::scoped_lock lock{read_mutex};
spsc_queue.Clear();
}
Slot<T>* slots; bool Empty() {
[[no_unique_address]] std::allocator<Slot<T>> allocator; std::scoped_lock lock{read_mutex};
return spsc_queue.Empty();
}
static_assert(std::is_nothrow_copy_assignable_v<T> || std::is_nothrow_move_assignable_v<T>, size_t Size() {
"T must be nothrow copy or move assignable"); std::scoped_lock lock{read_mutex};
return spsc_queue.Size();
}
static_assert(std::is_nothrow_destructible_v<T>, "T must be nothrow destructible"); private:
SPSCQueue<T, Capacity> spsc_queue;
std::mutex write_mutex;
std::mutex read_mutex;
}; };
} // namespace Common } // namespace Common

@ -31,9 +31,10 @@ static void RunThread(std::stop_token stop_token, Core::System& system,
auto current_context = context.Acquire(); auto current_context = context.Acquire();
VideoCore::RasterizerInterface* const rasterizer = renderer.ReadRasterizer(); VideoCore::RasterizerInterface* const rasterizer = renderer.ReadRasterizer();
while (!stop_token.stop_requested()) {
CommandDataContainer next; CommandDataContainer next;
state.queue.Pop(next, stop_token);
while (!stop_token.stop_requested()) {
state.queue.PopWait(next, stop_token);
if (stop_token.stop_requested()) { if (stop_token.stop_requested()) {
break; break;
} }
@ -117,7 +118,7 @@ u64 ThreadManager::PushCommand(CommandData&& command_data, bool block) {
std::unique_lock lk(state.write_lock); std::unique_lock lk(state.write_lock);
const u64 fence{++state.last_fence}; const u64 fence{++state.last_fence};
state.queue.Push(CommandDataContainer(std::move(command_data), fence, block)); state.queue.Push(std::move(command_data), fence, block);
if (block) { if (block) {
Common::CondvarWait(state.cv, lk, thread.get_stop_token(), [this, fence] { Common::CondvarWait(state.cv, lk, thread.get_stop_token(), [this, fence] {

Loading…
Cancel
Save