blob: 6e136e93445087db5567d99a7129b1552c16b37f (
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
|
#ifndef FUTURE_SCHEDULER_H
#define FUTURE_SCHEDULER_H
#include <functional>
#include <QtConcurrent/QtConcurrent>
#include <QFuture>
#include <QJSValue>
#include <QMutex>
#include <QMutexLocker>
#include <QPair>
#include <QWaitCondition>
class FutureScheduler : public QObject
{
Q_OBJECT
public:
FutureScheduler(QObject *parent);
~FutureScheduler();
void shutdownWaitForFinished() noexcept;
QPair<bool, QFuture<void>> run(std::function<void()> function) noexcept;
QPair<bool, QFuture<QJSValueList>> run(std::function<QJSValueList()> function, const QJSValue &callback);
bool stopping() const noexcept;
private:
bool add() noexcept;
void done() noexcept;
template<typename T>
QPair<bool, QFuture<T>> execute(std::function<QFuture<T>(QFutureWatcher<T> *)> makeFuture) noexcept
{
if (add())
{
try
{
auto *watcher = new QFutureWatcher<T>();
connect(watcher, &QFutureWatcher<T>::finished, [watcher] {
watcher->deleteLater();
});
watcher->setFuture(makeFuture(watcher));
return qMakePair(true, watcher->future());
}
catch (const std::exception &exception)
{
qCritical() << "Failed to schedule async function: " << exception.what();
done();
}
}
return qMakePair(false, QFuture<T>());
}
private:
size_t Alive;
QWaitCondition Condition;
QMutex Mutex;
std::atomic<bool> Stopping;
};
#endif // FUTURE_SCHEDULER_H
|