swift
threadutils.h
Go to the documentation of this file.
1 // SPDX-FileCopyrightText: Copyright (C) 2015 swift Project Community / Contributors
2 // SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-swift-pilot-client-1
3 
5 
6 #ifndef SWIFT_MISC_THREADUTILS_H
7 #define SWIFT_MISC_THREADUTILS_H
8 
9 #include <functional>
10 
11 #include <QMetaObject>
12 #include <QObject>
13 #include <QSharedPointer>
14 #include <QThread>
15 #include <QTimer>
16 
17 #include "misc/promise.h"
18 #include "misc/stacktrace.h"
19 #include "misc/swiftmiscexport.h"
20 
21 namespace swift::misc
22 {
29  template <typename F>
30  auto singleShot(int msec, QObject *target, F &&task)
31  {
32  CPromise<decltype(task())> promise;
33  QSharedPointer<QTimer> timer(new QTimer,
34  [](QObject *o) { QMetaObject::invokeMethod(o, &QObject::deleteLater); });
35  timer->setSingleShot(true);
36  timer->moveToThread(target->thread());
37  QObject::connect(timer.data(), &QTimer::timeout, target,
38  [trace = getStackTrace(), task = std::forward<F>(task), timer, promise]() mutable {
39  static_cast<void>(trace);
40  timer.clear();
41  promise.setResultFrom(task);
42  });
43  QMetaObject::invokeMethod(timer.data(), [t = timer.data(), msec] { t->start(msec); });
44  return promise.future();
45  }
46 
51  {
52  public:
54  CThreadUtils() = delete;
55 
59  static bool isInThisThread(const QObject *toBeTested);
60 
64  static bool thisIsMainThread();
65 
67  static QString currentThreadInfo();
68  };
69 } // namespace swift::misc
70 
71 #endif // SWIFT_MISC_THREADUTILS_H
A promise-based interface to QFuture, similar to std::promise for std::future.
Definition: promise.h:78
QFuture< T > future()
Return a future that can be used to access the result.
Definition: promise.h:81
void setResultFrom(F &&func)
Invoke a functor and use its return value to set the result.
Definition: promise.h:111
Utility class for threaded operations.
Definition: threadutils.h:51
CThreadUtils()=delete
No constructor.
Free functions in swift::misc.
QStringList getStackTrace()
Returns a stack trace of the current thread of execution as a list of function names.
Definition: stacktrace.cpp:39
auto singleShot(int msec, QObject *target, F &&task)
Starts a single-shot timer which will call a task in the thread of the given object when it times out...
Definition: threadutils.h:30
#define SWIFT_MISC_EXPORT
Export a class or function from the library.