2020-12-30 01:36:35 +01:00
|
|
|
// Copyright 2020 yuzu emulator team
|
|
|
|
// Licensed under GPLv2 or any later version
|
|
|
|
// Refer to the license.txt file included.
|
|
|
|
|
|
|
|
#include "common/thread.h"
|
|
|
|
#include "common/thread_worker.h"
|
|
|
|
|
|
|
|
namespace Common {
|
|
|
|
|
|
|
|
ThreadWorker::ThreadWorker(std::size_t num_workers, const std::string& name) {
|
2021-04-01 06:05:45 +02:00
|
|
|
const auto lambda = [this, thread_name{std::string{name}}] {
|
|
|
|
Common::SetCurrentThreadName(thread_name.c_str());
|
2020-12-30 01:36:35 +01:00
|
|
|
|
2021-04-01 06:05:45 +02:00
|
|
|
while (!stop) {
|
|
|
|
UniqueFunction<void> task;
|
2020-12-30 01:36:35 +01:00
|
|
|
{
|
|
|
|
std::unique_lock lock{queue_mutex};
|
2021-04-01 06:05:45 +02:00
|
|
|
if (requests.empty()) {
|
|
|
|
wait_condition.notify_all();
|
|
|
|
}
|
2020-12-30 01:36:35 +01:00
|
|
|
condition.wait(lock, [this] { return stop || !requests.empty(); });
|
2021-04-01 06:05:45 +02:00
|
|
|
if (stop || requests.empty()) {
|
|
|
|
break;
|
2020-12-30 01:36:35 +01:00
|
|
|
}
|
2021-04-01 06:05:45 +02:00
|
|
|
task = std::move(requests.front());
|
|
|
|
requests.pop();
|
2020-12-30 01:36:35 +01:00
|
|
|
}
|
2021-04-01 06:05:45 +02:00
|
|
|
task();
|
|
|
|
}
|
|
|
|
wait_condition.notify_all();
|
|
|
|
};
|
|
|
|
for (size_t i = 0; i < num_workers; ++i) {
|
|
|
|
threads.emplace_back(lambda);
|
|
|
|
}
|
2020-12-30 01:36:35 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
ThreadWorker::~ThreadWorker() {
|
|
|
|
{
|
|
|
|
std::unique_lock lock{queue_mutex};
|
|
|
|
stop = true;
|
|
|
|
}
|
|
|
|
condition.notify_all();
|
|
|
|
for (std::thread& thread : threads) {
|
|
|
|
thread.join();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-04-01 06:05:45 +02:00
|
|
|
void ThreadWorker::QueueWork(UniqueFunction<void> work) {
|
2020-12-30 01:36:35 +01:00
|
|
|
{
|
|
|
|
std::unique_lock lock{queue_mutex};
|
2021-04-01 06:05:45 +02:00
|
|
|
requests.emplace(std::move(work));
|
2020-12-30 01:36:35 +01:00
|
|
|
}
|
|
|
|
condition.notify_one();
|
|
|
|
}
|
|
|
|
|
2021-03-23 01:00:48 +01:00
|
|
|
void ThreadWorker::WaitForRequests() {
|
|
|
|
std::unique_lock lock{queue_mutex};
|
|
|
|
wait_condition.wait(lock, [this] { return stop || requests.empty(); });
|
|
|
|
}
|
|
|
|
|
2020-12-30 01:36:35 +01:00
|
|
|
} // namespace Common
|