2022-07-27 20:06:50 +02:00
|
|
|
// SPDX-FileCopyrightText: 2018 Citra Emulator Project
|
|
|
|
// SPDX-License-Identifier: GPL-2.0-or-later
|
2020-12-28 16:15:37 +01:00
|
|
|
|
|
|
|
#include <thread>
|
|
|
|
#include "common/assert.h"
|
|
|
|
#include "common/detached_tasks.h"
|
|
|
|
|
|
|
|
namespace Common {
|
|
|
|
|
|
|
|
DetachedTasks* DetachedTasks::instance = nullptr;
|
|
|
|
|
|
|
|
DetachedTasks::DetachedTasks() {
|
|
|
|
ASSERT(instance == nullptr);
|
|
|
|
instance = this;
|
|
|
|
}
|
|
|
|
|
|
|
|
void DetachedTasks::WaitForAllTasks() {
|
|
|
|
std::unique_lock lock{mutex};
|
|
|
|
cv.wait(lock, [this]() { return count == 0; });
|
|
|
|
}
|
|
|
|
|
|
|
|
DetachedTasks::~DetachedTasks() {
|
2021-06-23 14:35:57 +02:00
|
|
|
WaitForAllTasks();
|
|
|
|
|
2020-12-28 16:15:37 +01:00
|
|
|
std::unique_lock lock{mutex};
|
|
|
|
ASSERT(count == 0);
|
|
|
|
instance = nullptr;
|
|
|
|
}
|
|
|
|
|
|
|
|
void DetachedTasks::AddTask(std::function<void()> task) {
|
|
|
|
std::unique_lock lock{instance->mutex};
|
|
|
|
++instance->count;
|
|
|
|
std::thread([task{std::move(task)}]() {
|
|
|
|
task();
|
2022-06-15 19:54:21 +02:00
|
|
|
std::unique_lock thread_lock{instance->mutex};
|
2020-12-28 16:15:37 +01:00
|
|
|
--instance->count;
|
2022-06-15 19:54:21 +02:00
|
|
|
std::notify_all_at_thread_exit(instance->cv, std::move(thread_lock));
|
2020-12-28 16:15:37 +01:00
|
|
|
}).detach();
|
|
|
|
}
|
|
|
|
|
|
|
|
} // namespace Common
|