aboutsummaryrefslogtreecommitdiffstats
path: root/src/libs/utils/asynctask.h
blob: a600a14b24792f1a40e454c6a0466da03ef298d8 (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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
// 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 "tasktree.h"

#include <QFutureWatcher>
#include <QtConcurrent>

namespace Utils {

QTCREATOR_UTILS_EXPORT QThreadPool *asyncThreadPool(QThread::Priority priority);

template <typename Function, typename ...Args>
auto asyncRun(QThreadPool *threadPool, QThread::Priority priority,
              Function &&function, Args &&...args)
{
    QThreadPool *pool = threadPool ? threadPool : asyncThreadPool(priority);
    return QtConcurrent::run(pool, std::forward<Function>(function), std::forward<Args>(args)...);
}

template <typename Function, typename ...Args>
auto asyncRun(QThread::Priority priority, Function &&function, Args &&...args)
{
    return asyncRun<Function, Args...>(nullptr, priority,
                    std::forward<Function>(function), std::forward<Args>(args)...);
}

template <typename Function, typename ...Args>
auto asyncRun(QThreadPool *threadPool, Function &&function, Args &&...args)
{
    return asyncRun<Function, Args...>(threadPool, QThread::InheritPriority,
                    std::forward<Function>(function), std::forward<Args>(args)...);
}

template <typename Function, typename ...Args>
auto asyncRun(Function &&function, Args &&...args)
{
    return asyncRun<Function, Args...>(nullptr, QThread::InheritPriority,
                                       std::forward<Function>(function), std::forward<Args>(args)...);
}

class QTCREATOR_UTILS_EXPORT AsyncTaskBase : public QObject
{
    Q_OBJECT

signals:
    void started();
    void done();
    void resultReadyAt(int index);
};

template <typename ResultType>
class AsyncTask : public AsyncTaskBase
{
public:
    AsyncTask() {
        connect(&m_watcher, &QFutureWatcherBase::finished, this, &AsyncTaskBase::done);
        connect(&m_watcher, &QFutureWatcherBase::resultReadyAt,
                this, &AsyncTaskBase::resultReadyAt);
    }
    ~AsyncTask()
    {
        if (isDone())
            return;

        m_watcher.cancel();
        if (!m_synchronizer)
            m_watcher.waitForFinished();
    }

    template <typename Function, typename ...Args>
    void setConcurrentCallData(Function &&function, Args &&...args)
    {
        return wrapConcurrent(std::forward<Function>(function), std::forward<Args>(args)...);
    }

    void setFutureSynchronizer(FutureSynchronizer *synchorizer) { m_synchronizer = synchorizer; }
    void setThreadPool(QThreadPool *pool) { m_threadPool = pool; }
    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(); }
    ResultType resultAt(int index) const { return m_watcher.resultAt(index); }
    QList<ResultType> results() const { return future().results(); }
    bool isResultAvailable() const { return future().resultCount(); }

private:
    template <typename Function, typename ...Args>
    void wrapConcurrent(Function &&function, Args &&...args)
    {
        m_startHandler = [=] {
            return asyncRun(m_threadPool, m_priority, function, args...);
        };
    }

    template <typename Function, typename ...Args>
    void wrapConcurrent(std::reference_wrapper<const Function> &&wrapper, Args &&...args)
    {
        m_startHandler = [=] {
            return asyncRun(m_threadPool, m_priority, std::forward<const Function>(wrapper.get()),
                            args...);
        };
    }

    using StartHandler = std::function<QFuture<ResultType>()>;
    StartHandler m_startHandler;
    FutureSynchronizer *m_synchronizer = nullptr;
    QThreadPool *m_threadPool = nullptr;
    QThread::Priority m_priority = QThread::InheritPriority;
    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);