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
|
// Copyright (C) 2022 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
#pragma once
#include "utils_global.h"
#include "futuresynchronizer.h"
#include "qtcassert.h"
#include "runextensions.h"
#include "tasktree.h"
#include <QFutureWatcher>
namespace Utils {
class QTCREATOR_UTILS_EXPORT AsyncTaskBase : public QObject
{
Q_OBJECT
signals:
void started();
void done();
};
template <typename ResultType>
class AsyncTask : public AsyncTaskBase
{
public:
AsyncTask() { connect(&m_watcher, &QFutureWatcherBase::finished, this, &AsyncTaskBase::done); }
~AsyncTask()
{
if (isDone())
return;
m_watcher.cancel();
if (!m_synchronizer)
m_watcher.waitForFinished();
}
using StartHandler = std::function<QFuture<ResultType>()>;
template <typename Function, typename ...Args>
void setAsyncCallData(const Function &function, const Args &...args)
{
m_startHandler = [=] {
return Internal::runAsync_internal(m_threadPool, m_stackSize, m_priority,
function, args...);
};
}
void setFutureSynchronizer(FutureSynchronizer *synchorizer) { m_synchronizer = synchorizer; }
void setThreadPool(QThreadPool *pool) { m_threadPool = pool; }
void setStackSizeInBytes(const StackSizeInBytes &size) { m_stackSize = size; }
void setPriority(QThread::Priority priority) { m_priority = priority; }
void start()
{
QTC_ASSERT(m_startHandler, qWarning("No start handler specified."); return);
m_watcher.setFuture(m_startHandler());
emit started();
if (m_synchronizer)
m_synchronizer->addFuture(m_watcher.future());
}
bool isDone() const { return m_watcher.isFinished(); }
bool isCanceled() const { return m_watcher.isCanceled(); }
QFuture<ResultType> future() const { return m_watcher.future(); }
ResultType result() const { return m_watcher.result(); } // TODO: warn when isRunning?
QList<ResultType> results() const { return m_watcher.future().results(); }
private:
StartHandler m_startHandler;
FutureSynchronizer *m_synchronizer = nullptr;
QThreadPool *m_threadPool = nullptr;
QThread::Priority m_priority = QThread::InheritPriority;
StackSizeInBytes m_stackSize = {};
QFutureWatcher<ResultType> m_watcher;
};
template <typename ResultType>
class AsyncTaskAdapter : public Tasking::TaskAdapter<AsyncTask<ResultType>>
{
public:
AsyncTaskAdapter() {
this->connect(this->task(), &AsyncTaskBase::done, this, [this] {
emit this->done(!this->task()->isCanceled());
});
}
void start() final { this->task()->start(); }
};
} // namespace Utils
QTC_DECLARE_CUSTOM_TEMPLATE_TASK(Async, AsyncTaskAdapter);
|