aboutsummaryrefslogtreecommitdiff
path: root/src/common/detached_tasks.cpp
blob: f2ed795cc2a372111b9a15d2887b2c75f893c668 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// SPDX-FileCopyrightText: 2018 Citra Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#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() {
    WaitForAllTasks();

    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_();
        std::unique_lock thread_lock{instance->mutex};
        --instance->count;
        std::notify_all_at_thread_exit(instance->cv, std::move(thread_lock));
    }).detach();
}

} // namespace Common