aboutsummaryrefslogtreecommitdiff
path: root/src/qt/FutureScheduler.cpp
blob: 3ce8609470e05a1bbd1adef4cc240aaab42581a3 (plain)
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include "FutureScheduler.h"

#include <mutex>

#include <QThreadPool>

FutureScheduler::FutureScheduler(QObject *parent)
    : QObject(parent), Alive(0), Stopping(false)
{
    static std::once_flag once;
    std::call_once(once, []() {
        QThreadPool::globalInstance()->setMaxThreadCount(4);
    });
}

FutureScheduler::~FutureScheduler()
{
    shutdownWaitForFinished();
}

void FutureScheduler::shutdownWaitForFinished() noexcept
{
    QMutexLocker locker(&Mutex);

    Stopping = true;
    while (Alive > 0)
    {
        Condition.wait(&Mutex);
    }
}

QPair<bool, QFuture<void>> FutureScheduler::run(std::function<void()> function) noexcept
{
    return execute<void>([this, function](QFutureWatcher<void> *) {
        return QtConcurrent::run([this, function] {
            try
            {
                function();
            }
            catch (const std::exception &exception)
            {
                qWarning() << "Exception thrown from async function: " << exception.what();
            }
            done();
        });
    });
}

QPair<bool, QFuture<QJSValueList>> FutureScheduler::run(std::function<QJSValueList()> function, const QJSValue &callback)
{
    if (!callback.isCallable())
    {
        throw std::runtime_error("js callback must be callable");
    }

    return execute<QJSValueList>([this, function, callback](QFutureWatcher<QJSValueList> *watcher) {
        connect(watcher, &QFutureWatcher<QJSValueList>::finished, [watcher, callback] {
            QJSValue(callback).call(watcher->future().result());
        });
        return QtConcurrent::run([this, function] {
            QJSValueList result;
            try
            {
                result = function();
            }
            catch (const std::exception &exception)
            {
                qWarning() << "Exception thrown from async function: " << exception.what();
            }
            done();
            return result;
        });
    });
}

bool FutureScheduler::stopping() const noexcept
{
    return Stopping;
}

bool FutureScheduler::add() noexcept
{
    QMutexLocker locker(&Mutex);

    if (Stopping)
    {
        return false;
    }

    ++Alive;
    return true;
}

void FutureScheduler::done() noexcept
{
    {
        QMutexLocker locker(&Mutex);
        --Alive;
    }

    Condition.wakeAll();
}