// Copyright 2020 yuzu emulator team // Licensed under GPLv2 or any later version // Refer to the license.txt file included. #pragma once #include #include #include #include #include #include #include #include "common/thread.h" #include "common/unique_function.h" namespace Common { template class StatefulThreadWorker { static constexpr bool with_state = !std::is_same_v; struct DummyCallable { int operator()() const noexcept { return 0; } }; using Task = std::conditional_t, UniqueFunction>; using StateMaker = std::conditional_t, DummyCallable>; public: explicit StatefulThreadWorker(size_t num_workers, std::string name, StateMaker func = {}) : workers_queued{num_workers}, thread_name{std::move(name)} { const auto lambda = [this, func] { Common::SetCurrentThreadName(thread_name.c_str()); { std::conditional_t state{func()}; while (!stop) { Task task; { std::unique_lock lock{queue_mutex}; if (requests.empty()) { wait_condition.notify_all(); } condition.wait(lock, [this] { return stop || !requests.empty(); }); if (stop) { break; } task = std::move(requests.front()); requests.pop(); } if constexpr (with_state) { task(&state); } else { task(); } ++work_done; } } ++workers_stopped; wait_condition.notify_all(); }; for (size_t i = 0; i < num_workers; ++i) { threads.emplace_back(lambda); } } ~StatefulThreadWorker() { { std::unique_lock lock{queue_mutex}; stop = true; } condition.notify_all(); for (std::thread& thread : threads) { thread.join(); } } void QueueWork(Task work) { { std::unique_lock lock{queue_mutex}; requests.emplace(std::move(work)); ++work_scheduled; } condition.notify_one(); } void WaitForRequests() { std::unique_lock lock{queue_mutex}; wait_condition.wait(lock, [this] { return workers_stopped >= workers_queued || work_done >= work_scheduled; }); } private: std::vector threads; std::queue requests; std::mutex queue_mutex; std::condition_variable condition; std::condition_variable wait_condition; std::atomic_bool stop{}; std::atomic work_scheduled{}; std::atomic work_done{}; std::atomic workers_stopped{}; std::atomic workers_queued{}; std::string thread_name; }; using ThreadWorker = StatefulThreadWorker<>; } // namespace Common