File: dthreadutils.h

package info (click to toggle)
dtkcore 5.7.12-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,728 kB
  • sloc: cpp: 22,021; ansic: 183; python: 68; xml: 58; makefile: 27; sh: 15
file content (328 lines) | stat: -rw-r--r-- 11,939 bytes parent folder | download
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
// SPDX-FileCopyrightText: 2020 - 2023 UnionTech Software Technology Co., Ltd.
//
// SPDX-License-Identifier: LGPL-3.0-or-later

#ifndef DTHREADUTILS_H
#define DTHREADUTILS_H

#include <dtkcore_global.h>
#include <QObject>
#include <QSemaphore>
#include <QThread>
#include <QCoreApplication>
#include <QPointer>
#include <QDebug>

#if DTK_VERSION >= DTK_VERSION_CHECK(6, 0, 0, 0)
#include <QFuture>
#include <QPromise>
#include <QEvent>
#endif

DCORE_BEGIN_NAMESPACE

#if DTK_VERSION < DTK_VERSION_CHECK(6, 0, 0, 0)
namespace DThreadUtil {
typedef std::function<void()> FunctionType;

class LIBDTKCORESHARED_EXPORT FunctionCallProxy : public QObject
{
    Q_OBJECT
public:
    explicit FunctionCallProxy(QThread *thread);

    static void proxyCall(QSemaphore *s, QThread *thread, QObject *target, FunctionType fun);

Q_SIGNALS:
    void callInLiveThread(QSemaphore *s, QPointer<QObject> target, FunctionType *func);
};

template <typename ReturnType>
class LIBDTKCORESHARED_EXPORT _TMP
{
public:
    inline static ReturnType runInThread(QSemaphore *s, QThread *thread, QObject *target, std::function<ReturnType()> fun)
    {
        ReturnType result;
        FunctionType proxyFun = [&result, &fun] () {
            result = fun();
        };

        FunctionCallProxy::proxyCall(s, thread, target, proxyFun);
        return result;
    }

    template <typename T>
    inline static typename std::enable_if<!std::is_base_of<QObject, T>::value, ReturnType>::type
            runInThread(QSemaphore *s, QThread *thread, T *, std::function<ReturnType()> fun)
    {
        return runInThread(s, thread, static_cast<QObject*>(nullptr), fun);
    }
};
template <>
class LIBDTKCORESHARED_EXPORT _TMP<void>
{
public:
    inline static void runInThread(QSemaphore *s, QThread *thread, QObject *target, std::function<void()> fun)
    {
        FunctionCallProxy::proxyCall(s, thread, target, fun);
    }

    template <typename T>
    inline static typename std::enable_if<!std::is_base_of<QObject, T>::value, void>::type
            runInThread(QSemaphore *s, QThread *thread, T *, std::function<void()> fun)
    {
        return runInThread(s, thread, static_cast<QObject*>(nullptr), fun);
    }
};

template <typename Fun, typename... Args>
inline auto runInThread(QSemaphore *s, QThread *thread, QObject *target, Fun fun, Args&&... args) -> decltype(fun(args...))
{
    return _TMP<decltype(fun(args...))>::runInThread(s, thread, target, std::bind(fun, std::forward<Args>(args)...));
}
template <typename Fun, typename... Args>
inline auto runInThread(QSemaphore *s, QThread *thread, Fun fun, Args&&... args) -> decltype(fun(args...))
{
    return runInThread(s, thread, nullptr, fun, std::forward<Args>(args)...);
}
template <typename Fun, typename... Args>
inline typename QtPrivate::FunctionPointer<Fun>::ReturnType
        runInThread(QSemaphore *s, QThread *thread, QObject *target, typename QtPrivate::FunctionPointer<Fun>::Object *obj, Fun fun, Args&&... args)
{
    return _TMP<typename QtPrivate::FunctionPointer<Fun>::ReturnType>::runInThread(s, thread, target, std::bind(fun, obj, std::forward<Args>(args)...));
}
template <typename Fun, typename... Args>
inline typename QtPrivate::FunctionPointer<Fun>::ReturnType
        runInThread(QSemaphore *s, QThread *thread, typename QtPrivate::FunctionPointer<Fun>::Object *obj, Fun fun, Args&&... args)
{
    return _TMP<typename QtPrivate::FunctionPointer<Fun>::ReturnType>::runInThread(s, thread, obj, std::bind(fun, obj, std::forward<Args>(args)...));
}

template <typename Fun, typename... Args>
inline auto runInThread(QThread *thread, QObject *target, Fun fun, Args&&... args) -> decltype(fun(args...))
{
    QSemaphore s;

    return runInThread(&s, thread, target, fun, std::forward<Args>(args)...);
}
template <typename Fun, typename... Args>
inline auto runInThread(QThread *thread, Fun fun, Args&&... args) -> decltype(fun(args...))
{
    return runInThread(thread, nullptr, fun, std::forward<Args>(args)...);
}
template <typename T, typename Fun, typename... Args>
inline typename QtPrivate::FunctionPointer<Fun>::ReturnType
        runInThread(QThread *thread, T *target, typename QtPrivate::FunctionPointer<Fun>::Object *obj, Fun fun, Args&&... args)
{
    QSemaphore s;

    return runInThread(&s, thread, target, obj, fun, std::forward<Args>(args)...);
}

template <typename Fun, typename... Args>
inline typename QtPrivate::FunctionPointer<Fun>::ReturnType
        runInThread(QThread *thread, typename QtPrivate::FunctionPointer<Fun>::Object *obj, Fun fun, Args&&... args)
{
    return runInThread(thread, obj, obj, fun, std::forward<Args>(args)...);
}

template <typename Fun, typename... Args>
inline auto runInMainThread(QObject *target, Fun fun, Args&&... args) -> decltype(fun(args...))
{
    if (!QCoreApplication::instance()) {
        return fun(std::forward<Args>(args)...);
    }

    return runInThread(QCoreApplication::instance()->thread(), target, fun, std::forward<Args>(args)...);
}
template <typename Fun, typename... Args>
inline auto runInMainThread(Fun fun, Args&&... args) -> decltype(fun(args...))
{
    return runInMainThread(nullptr, fun, std::forward<Args>(args)...);
}

template <typename T, typename Fun, typename... Args>
inline typename QtPrivate::FunctionPointer<Fun>::ReturnType
        runInMainThread(T *target, typename QtPrivate::FunctionPointer<Fun>::Object *obj, Fun fun, Args&&... args)
{
    if (!QCoreApplication::instance()) {
        return (obj->*fun)(std::forward<Args>(args)...);
    }

    return runInThread(QCoreApplication::instance()->thread(), target, obj, fun, std::forward<Args>(args)...);
}
template <typename Fun, typename... Args>
inline typename QtPrivate::FunctionPointer<Fun>::ReturnType
        runInMainThread(typename QtPrivate::FunctionPointer<Fun>::Object *obj, Fun fun, Args&&... args)
{
    return runInMainThread(obj, obj, fun, std::forward<Args>(args)...);
}
}
#else
class LIBDTKCORESHARED_EXPORT DThreadUtils final
{
    friend class Caller;
public:
    explicit DThreadUtils(QThread *thread);
    ~DThreadUtils();

    static DThreadUtils &gui();

    QThread *thread() const noexcept;

    template <typename Func, typename... Args>
    inline auto run(QObject *context,typename QtPrivate::FunctionPointer<Func>::Object *obj, Func fun, Args &&...args)
    {
        return call(context, fun, *obj, std::forward<Args>(args)...);
    }
    template <typename Func, typename... Args>
    inline auto run(typename QtPrivate::FunctionPointer<Func>::Object *obj, Func fun, Args &&...args)
    {
        if constexpr (std::is_base_of<QObject, typename QtPrivate::FunctionPointer<Func>::Object>::value) {
            return call(obj, fun, *obj, std::forward<Args>(args)...);
        } else {
            return call(static_cast<QObject *>(nullptr), fun, *obj, std::forward<Args>(args)...);
        }
    }
    template <typename Func, typename... Args>
    inline QFuture<std::invoke_result_t<std::decay_t<Func>, Args...>> run(QObject *context, Func fun, Args &&...args)
    {
        return call(context, fun, std::forward<Args>(args)...);
    }
    template <typename Func, typename... Args>
    inline QFuture<std::invoke_result_t<std::decay_t<Func>, Args...>> run(Func fun, Args &&...args)
    {
        return call(static_cast<QObject *>(nullptr), fun, std::forward<Args>(args)...);
    }
    template <typename... T>
    inline decltype(auto) exec(T &&...args)
    {
        auto future = run(std::forward<T>(args)...);
        if (!thread()->isRunning()) {
            qWarning() << "The target thread is not running, maybe lead to deadlock.";
        }
        future.waitForFinished();
        if constexpr (std::is_same_v<decltype(future), QFuture<void>>) {
            return;
        } else {
            return future.result();
        }
    }

private:
    class AbstractCallEvent : public QEvent
    {
    public:
        AbstractCallEvent(QEvent::Type type)
            : QEvent(type)
        {
        }
        virtual void call() = 0;
    };

    template <typename Func, typename... Args>
    class Q_DECL_HIDDEN CallEvent : public AbstractCallEvent
    {
        using FunInfo = QtPrivate::FunctionPointer<std::decay_t<Func>>;
        using ReturnType = std::invoke_result_t<std::decay_t<Func>, Args...>;

    public:
        CallEvent(QEvent::Type type, Func &&fun, Args &&...args)
            : AbstractCallEvent(type)
            , function(std::forward<Func>(fun))
            , arguments(std::forward<Args>(args)...)
        {
        }

        QEvent *clone() const override { return nullptr; }

        void call() override
        {
            if (promise.isCanceled()) {
                return;
            }

            if (contextChecker == context) {
                promise.start();
#ifndef QT_NO_EXCEPTIONS
                try {
#endif
                    if constexpr (std::is_void_v<ReturnType>) {
                        std::apply(function, arguments);
                    } else {
                        promise.addResult(std::apply(function, arguments));
                    }
#ifndef QT_NO_EXCEPTIONS
                } catch (...) {
                    promise.setException(std::current_exception());
                }
#endif
                promise.finish();
            } else {
                promise.start();
                promise.setException(std::make_exception_ptr(std::runtime_error("The context object is destroyed.")));
                promise.finish();
            }
        }

        Func function;
        const std::tuple<Args...> arguments;
        QPromise<ReturnType> promise;

        QObject *context{nullptr};
        QPointer<QObject> contextChecker;
    };

    template <typename Func, typename... Args>
    inline auto call(QObject *context, Func fun, Args &&...args)
    {
        using FuncInfo = QtPrivate::FunctionPointer<std::decay_t<Func>>;
        using ReturnType = std::invoke_result_t<std::decay_t<Func>, Args...> ;

        if constexpr (FuncInfo::IsPointerToMemberFunction) {
            static_assert(std::is_same_v<std::decay_t<typename QtPrivate::List<Args...>::Car>, typename FuncInfo::Object>,
                          "The obj and function are not compatible.");
            static_assert(
                QtPrivate::CheckCompatibleArguments<typename QtPrivate::List<Args...>::Cdr, typename FuncInfo::Arguments>::value,
                "The args and function are not compatible.");
        } else if constexpr (FuncInfo::ArgumentCount != -1) {
            static_assert(QtPrivate::CheckCompatibleArguments<QtPrivate::List<Args...>, typename FuncInfo::Arguments>::value,
                          "The args and function are not compatible.");
        } else {  // for lambda and impl operator()
            static_assert(std::is_invocable_r_v<ReturnType, Func, Args...>,
                          "The callable object can't invoke with supplied args");
        }

        QPromise<ReturnType> promise;
        auto future = promise.future();

        if (Q_UNLIKELY(QThread::currentThread() == m_thread)) {
            promise.start();
            if constexpr (std::is_void_v<ReturnType>) {
                std::invoke(fun, std::forward<Args>(args)...);
            } else {
                promise.addResult(std::invoke(fun, std::forward<Args>(args)...));
            }
            promise.finish();
        } else {
            auto event = new CallEvent<Func, Args...>(eventType, std::move(fun), std::forward<Args>(args)...);
            event->promise = std::move(promise);
            event->context = context;
            event->contextChecker = context;

            QCoreApplication::postEvent(ensureThreadContextObject(), event);
        }

        return future;
    }

    QObject *ensureThreadContextObject();

    static inline QEvent::Type eventType;
    QThread *m_thread;
    QAtomicPointer<QObject> threadContext;
};
#endif // version macro end
DCORE_END_NAMESPACE
#endif // protect macro end