1
0
Fork 0
forked from suyu/suyu
suyu/src/common/detached_tasks.cpp

43 lines
1 KiB
C++
Raw Normal View History

2018-09-16 20:05:51 +02: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() {
std::unique_lock lock{mutex};
2018-09-16 20:05:51 +02:00
cv.wait(lock, [this]() { return count == 0; });
}
DetachedTasks::~DetachedTasks() {
WaitForAllTasks();
std::unique_lock lock{mutex};
2018-09-16 20:05:51 +02:00
ASSERT(count == 0);
instance = nullptr;
}
void DetachedTasks::AddTask(std::function<void()> task) {
std::unique_lock lock{instance->mutex};
2018-09-16 20:05:51 +02:00
++instance->count;
std::thread([task{std::move(task)}]() {
task();
std::unique_lock thread_lock{instance->mutex};
2018-09-16 20:05:51 +02:00
--instance->count;
std::notify_all_at_thread_exit(instance->cv, std::move(thread_lock));
}).detach();
2018-09-16 20:05:51 +02:00
}
} // namespace Common