2018-09-16 14:05:51 -04:00
|
|
|
// Copyright 2018 Citra Emulator Project
|
|
|
|
// Licensed under GPLv2 or any later version
|
|
|
|
// Refer to the license.txt file included.
|
|
|
|
|
|
|
|
#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() {
|
2019-04-01 12:29:59 -04:00
|
|
|
std::unique_lock lock{mutex};
|
2018-09-16 14:05:51 -04:00
|
|
|
cv.wait(lock, [this]() { return count == 0; });
|
|
|
|
}
|
|
|
|
|
|
|
|
DetachedTasks::~DetachedTasks() {
|
2021-06-22 03:27:44 -04:00
|
|
|
WaitForAllTasks();
|
|
|
|
|
2019-04-01 12:29:59 -04:00
|
|
|
std::unique_lock lock{mutex};
|
2018-09-16 14:05:51 -04:00
|
|
|
ASSERT(count == 0);
|
|
|
|
instance = nullptr;
|
|
|
|
}
|
|
|
|
|
|
|
|
void DetachedTasks::AddTask(std::function<void()> task) {
|
2019-04-01 12:29:59 -04:00
|
|
|
std::unique_lock lock{instance->mutex};
|
2018-09-16 14:05:51 -04:00
|
|
|
++instance->count;
|
|
|
|
std::thread([task{std::move(task)}]() {
|
|
|
|
task();
|
2022-05-26 20:33:55 -04:00
|
|
|
std::unique_lock thread_lock{instance->mutex};
|
2018-09-16 14:05:51 -04:00
|
|
|
--instance->count;
|
2022-05-26 20:33:55 -04:00
|
|
|
std::notify_all_at_thread_exit(instance->cv, std::move(thread_lock));
|
2020-08-11 11:08:10 -04:00
|
|
|
}).detach();
|
2018-09-16 14:05:51 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
} // namespace Common
|