Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qthread.h
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// Copyright (C) 2017 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Giuseppe D'Angelo <giuseppe.dangelo@kdab.com>
3// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
4// Qt-Security score:significant reason:default
5
6#ifndef QTHREAD_H
7#define QTHREAD_H
8
9#include <QtCore/qobject.h>
10#include <QtCore/qdeadlinetimer.h>
11
12// For QThread::create
13#include <future> // for std::async
14#include <functional> // for std::invoke; no guard needed as it's a C++98 header
15// internal compiler error with mingw 8.1
16#if defined(Q_CC_MSVC) && defined(Q_PROCESSOR_X86)
17#include <intrin.h>
18#endif
19
20QT_BEGIN_NAMESPACE
21
22
23class QThreadData;
24class QThreadPrivate;
25class QAbstractEventDispatcher;
27
28class Q_CORE_EXPORT QThread : public QObject
29{
30 Q_OBJECT
31public:
32 Q_DECL_PURE_FUNCTION static Qt::HANDLE currentThreadId() noexcept;
33#ifdef Q_CC_GNU
34 __attribute__((returns_nonnull))
35#endif
36 static QThread *currentThread();
37 static bool isMainThread() noexcept;
38 static int idealThreadCount() noexcept;
39 static void yieldCurrentThread();
40
41 explicit QThread(QObject *parent = nullptr);
42 ~QThread();
43
44 enum Priority {
45 IdlePriority,
46
47 LowestPriority,
48 LowPriority,
49 NormalPriority,
50 HighPriority,
51 HighestPriority,
52
53 TimeCriticalPriority,
54
55 InheritPriority
56 };
57
58 enum class QualityOfService {
59 Auto,
60 High,
61 Eco,
62 };
63 Q_ENUM(QualityOfService)
64
65 void setPriority(Priority priority);
66 Priority priority() const;
67
68 bool isFinished() const;
69 bool isRunning() const;
70
71 void requestInterruption();
72 bool isInterruptionRequested() const;
73
74 void setStackSize(uint stackSize);
75 uint stackSize() const;
76
77 QAbstractEventDispatcher *eventDispatcher() const;
78 void setEventDispatcher(QAbstractEventDispatcher *eventDispatcher);
79
80 bool event(QEvent *event) override;
81 int loopLevel() const;
82
83 bool isCurrentThread() const noexcept;
84
85 void setServiceLevel(QualityOfService serviceLevel);
86 QualityOfService serviceLevel() const;
87
88 template <typename Function, typename... Args>
89 [[nodiscard]] static QThread *create(Function &&f, Args &&... args);
90
91public Q_SLOTS:
92 void start(Priority = InheritPriority);
93 void terminate();
94 void exit(int retcode = 0);
95 void quit();
96
97public:
98 bool wait(QDeadlineTimer deadline = QDeadlineTimer(QDeadlineTimer::Forever));
99 bool wait(unsigned long time)
100 {
101 if (time == (std::numeric_limits<unsigned long>::max)())
102 return wait(QDeadlineTimer(QDeadlineTimer::Forever));
103 return wait(QDeadlineTimer(time));
104 }
105
106 static void sleep(unsigned long);
107 static void msleep(unsigned long);
108 static void usleep(unsigned long);
109 static void sleep(std::chrono::nanoseconds nsec);
110
111Q_SIGNALS:
112 void started(QPrivateSignal);
113 void finished(QPrivateSignal);
114
115protected:
116 virtual void run();
117 int exec();
118
119 static void setTerminationEnabled(bool enabled = true);
120
121protected:
122 QThread(QThreadPrivate &dd, QObject *parent = nullptr);
123
124private:
125 Q_DECLARE_PRIVATE(QThread)
126 friend class QEventLoopLocker;
127
128 [[nodiscard]] static QThread *createThreadImpl(std::future<void> &&future);
129 Q_DECL_PURE_FUNCTION static Qt::HANDLE currentThreadIdImpl() noexcept;
130
131 friend class QCoreApplication;
132 friend class QThreadData;
133};
134
135template <typename Function, typename... Args>
136QThread *QThread::create(Function &&f, Args &&... args)
137{
138 using DecayedFunction = typename std::decay<Function>::type;
139 auto threadFunction =
140 [f = static_cast<DecayedFunction>(std::forward<Function>(f))](auto &&... largs) mutable -> void
141 {
142 (void)std::invoke(std::move(f), std::forward<decltype(largs)>(largs)...);
143 };
144
145 return createThreadImpl(std::async(std::launch::deferred,
146 std::move(threadFunction),
147 std::forward<Args>(args)...));
148}
149
150/*
151 On architectures and platforms we know, interpret the thread control
152 block (TCB) as a unique identifier for a thread within a process. Otherwise,
153 fall back to a slower but safe implementation.
154
155 As per the documentation of currentThreadId, we return an opaque handle
156 as a thread identifier, and application code is not supposed to use that
157 value for anything. In Qt we use the handle to check if threads are identical,
158 for which the TCB is sufficient.
159
160 So we use the fastest possible way, rather than spend time on returning
161 some pseudo-interoperable value.
162*/
163inline Qt::HANDLE QThread::currentThreadId() noexcept
164{
165 // define is undefed if we have to fall back to currentThreadIdImpl
166#define QT_HAS_FAST_CURRENT_THREAD_ID
167 Qt::HANDLE tid; // typedef to void*
168 static_assert(sizeof(tid) == sizeof(void*));
169 // See https://akkadia.org/drepper/tls.pdf for x86 ABI
170#if defined(Q_PROCESSOR_X86_32) && ((defined(Q_OS_LINUX) && defined(__GLIBC__)) || defined(Q_OS_FREEBSD)) // x86 32-bit always uses GS
171 __asm__("mov %%gs:%c1, %0" : "=r" (tid) : "i" (2 * sizeof(void*)) : );
172#elif defined(Q_PROCESSOR_X86_64) && defined(Q_OS_DARWIN)
173 // 64bit macOS uses GS, see https://github.com/apple/darwin-xnu/blob/master/libsyscall/os/tsd.h
174 __asm__("mov %%gs:0, %0" : "=r" (tid) : : );
175#elif defined(Q_PROCESSOR_X86_64) && ((defined(Q_OS_LINUX) && defined(__GLIBC__)) || defined(Q_OS_FREEBSD))
176 // x86_64 Linux, BSD uses FS
177 __asm__("mov %%fs:%c1, %0" : "=r" (tid) : "i" (2 * sizeof(void*)) : );
178#elif defined(Q_PROCESSOR_X86_64) && defined(Q_OS_WIN) && defined(Q_CC_MSVC)
179 // See https://en.wikipedia.org/wiki/Win32_Thread_Information_Block
180 tid = reinterpret_cast<Qt::HANDLE>(__readgsqword(0x48));
181#elif defined(Q_PROCESSOR_X86_64) && defined(Q_OS_WIN) // !Q_CC_MSVC
182 __asm__("mov %%gs:0x48, %0" : "=r" (tid));
183#elif defined(Q_PROCESSOR_X86_32) && defined(Q_OS_WIN) && defined(Q_CC_MSVC)
184 tid = reinterpret_cast<Qt::HANDLE>(__readfsdword(0x24));
185#elif defined(Q_PROCESSOR_X86_32) && defined(Q_OS_WIN) // !Q_CC_MSVC
186 __asm__("mov %%fs:0x24, %0" : "=r" (tid));
187#else
188#undef QT_HAS_FAST_CURRENT_THREAD_ID
189 tid = currentThreadIdImpl();
190#endif
191 return tid;
192}
193
194QT_END_NAMESPACE
195
196#endif // QTHREAD_H
QByteArray::Base64DecodingStatus decodingStatus
Definition qbytearray.h:827
friend bool operator==(const QByteArray::FromBase64Result &lhs, const QByteArray::FromBase64Result &rhs) noexcept
Returns true if lhs and rhs are equal, otherwise returns false.
Definition qbytearray.h:842
QByteArray & operator*() &noexcept
Definition qbytearray.h:837
const QByteArray & operator*() const &noexcept
Definition qbytearray.h:838
void swap(QByteArray::FromBase64Result &other) noexcept
Definition qbytearray.h:829
operator bool() const noexcept
\variable QByteArray::FromBase64Result::decoded
Definition qbytearray.h:835
QByteArray && operator*() &&noexcept
Definition qbytearray.h:839
const QByteArray && operator*() const &&noexcept
Definition qbytearray.h:840
friend bool operator!=(const QByteArray::FromBase64Result &lhs, const QByteArray::FromBase64Result &rhs) noexcept
Returns true if lhs and rhs are different, otherwise returns false.
Definition qbytearray.h:853
\inmodule QtCore
Definition qbytearray.h:58
\inmodule QtCore\reentrant
Definition qdatastream.h:50
\inmodule QtCore
Definition qeventloop.h:60
int initFrom(const QMessageLogContext &logContext)
void populateBacktrace(int frameCount)
QInternalMessageLogContext(const QMessageLogContext &logContext, const QLoggingCategory &categoryOverride)
Definition qlogging_p.h:67
static constexpr int MaxBacktraceDepth
Definition qlogging_p.h:49
std::optional< BacktraceStorage > backtrace
Definition qlogging_p.h:59
static constexpr int DefaultBacktraceDepth
Definition qlogging_p.h:48
Definition qlist.h:82
\inmodule QtCore
Definition qlogging.h:44
constexpr QMessageLogContext(const char *fileName, int lineNumber, const char *functionName, const char *categoryName) noexcept
Definition qlogging.h:49
const char * category
Definition qlogging.h:56
constexpr QMessageLogContext() noexcept=default
const char * function
Definition qlogging.h:55
const char * file
Definition qlogging.h:54
\inmodule QtCore
Definition qlogging.h:74
QDebug debug(CategoryFunction catFunc) const
QDebug debug(const QLoggingCategory &cat) const
Logs a debug message into category cat using a QDebug stream.
Definition qlogging.cpp:528
void void void void Q_DECL_COLD_FUNCTION void Q_DECL_COLD_FUNCTION void Q_DECL_COLD_FUNCTION void Q_DECL_COLD_FUNCTION void QT_MESSAGE_LOGGER_NORETURN Q_DECL_COLD_FUNCTION void QT_MESSAGE_LOGGER_NORETURN Q_DECL_COLD_FUNCTION void QDebug debug() const
Logs a debug message using a QDebug stream.
Definition qlogging.cpp:514
QDebug info(const QLoggingCategory &cat) const
Logs an informational message into the category cat using a QDebug stream.
Definition qlogging.cpp:617
QDebug info() const
Logs an informational message using a QDebug stream.
Definition qlogging.cpp:603
QNoDebug noDebug(...) const noexcept
QDebug info(CategoryFunction catFunc) const
\macro QT_RESTRICTED_CAST_FROM_ASCII
Definition qstring.h:177
static const char ifCriticalTokenC[]
static bool grabMessageHandler()
void qt_message_output(QtMsgType msgType, const QMessageLogContext &context, const QString &message)
static const char emptyTokenC[]
static Q_NEVER_INLINE void qt_message(QtMsgType msgType, const QMessageLogContext &context, const char *msg, va_list ap)
Definition qlogging.cpp:411
static void preformattedMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &formattedMessage)
static bool systemHasStderr()
Returns true if writing to stderr is supported.
Definition qlogging.cpp:267
static const char endifTokenC[]
static bool isDefaultCategory(const char *category)
Definition qlogging.cpp:957
static const char messageTokenC[]
static bool qt_append_thread_name_to(QString &message)
Definition qlogging.cpp:252
static void qt_maybe_message_fatal(QtMsgType, const QMessageLogContext &context, String &&message)
\inmodule QtCore \title Qt Logging Types
#define HANDLE_IF_TOKEN(LEVEL)
Q_DECLARE_TYPEINFO(QMessagePattern::BacktraceParams, Q_RELOCATABLE_TYPE)
static void qDefaultMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &buf)
static constexpr auto systemMessageSink()
static const char timeTokenC[]
static bool isFatalCountDown(const char *varname, QBasicAtomicInt &n)
Definition qlogging.cpp:157
void qErrnoWarning(int code, const char *msg,...)
static const char qthreadptrTokenC[]
static const char fileTokenC[]
static const char ifDebugTokenC[]
static const char ifFatalTokenC[]
static const char categoryTokenC[]
static void stderr_message_handler(QtMsgType type, const QMessageLogContext &context, const QString &formattedMessage)
static const char lineTokenC[]
static const char typeTokenC[]
static void ungrabMessageHandler()
static void copyInternalContext(QInternalMessageLogContext *self, const QMessageLogContext &logContext) noexcept
static const char ifCategoryTokenC[]
static int checked_var_value(const char *varname)
Definition qlogging.cpp:143
static const char threadnameTokenC[]
static const char pidTokenC[]
Q_TRACE_POINT(qtcore, qt_message_print, int type, const char *category, const char *function, const char *file, int line, const QString &message)
static const char threadidTokenC[]
static QString formatLogMessage(QtMsgType type, const QMessageLogContext &context, const QString &str)
static Q_CONSTINIT bool msgHandlerGrabbed
static const char backtraceTokenC[]
void qErrnoWarning(const char *msg,...)
static const char functionTokenC[]
#define IF_TOKEN(LEVEL)
static const char ifWarningTokenC[]
static const char appnameTokenC[]
static bool isFatal(QtMsgType msgType)
Definition qlogging.cpp:191
static const char ifInfoTokenC[]
QtMessageHandler qInstallMessageHandler(QtMessageHandler h)
static void qt_message_print(QtMsgType, const QMessageLogContext &context, const QString &message)
static bool stderrHasConsoleAttached()
Returns true if writing to stderr will end up in a console/terminal visible to the user.
Definition qlogging.cpp:296
void qSetMessagePattern(const QString &pattern)
Combined button and popup list for selecting options.
QDebug printAssociativeContainer(QDebug debug, const char *which, const AssociativeContainer &c)
Definition qdebug.h:393
bool shouldLogToStderr()
Returns true if logging stderr should be ensured.
Definition qlogging.cpp:343
QDebug printSequentialContainer(QDebug debug, const char *which, const SequentialContainer &c)
Definition qdebug.h:375
Definition qcompare.h:111
QT_BEGIN_NAMESPACE Q_NORETURN void qAbort()
Definition qassert.cpp:25
QByteArray operator+(const QByteArray &a1, const char *a2)
Definition qbytearray.h:748
QByteArray qUncompress(const QByteArray &data)
Definition qbytearray.h:817
QByteArray operator+(char a1, const QByteArray &a2)
Definition qbytearray.h:758
QByteArray operator+(QByteArray &&lhs, char rhs)
Definition qbytearray.h:754
QByteArray operator+(const QByteArray &a1, char a2)
Definition qbytearray.h:752
QByteArray operator+(const char *a1, const QByteArray &a2)
Definition qbytearray.h:756
QByteArray operator+(QByteArray &&lhs, const QByteArray &rhs)
Definition qbytearray.h:746
qsizetype erase_if(QByteArray &ba, Predicate pred)
Definition qbytearray.h:871
QByteArray operator+(const QByteArray &a1, const QByteArray &a2)
Definition qbytearray.h:744
QByteArray qCompress(const QByteArray &data, int compressionLevel=-1)
Definition qbytearray.h:815
#define QT5_NULL_STRINGS
Definition qbytearray.h:26
qsizetype erase(QByteArray &ba, const T &t)
Definition qbytearray.h:865
QByteArray operator+(QByteArray &&lhs, const char *rhs)
Definition qbytearray.h:750
#define __has_builtin(x)
#define __has_include(x)
void qt_QMetaEnum_flagDebugOperator(QDebug &debug, size_t sizeofT, Int value)
Definition qdebug.h:622
Q_CORE_EXPORT void qt_QMetaEnum_flagDebugOperator(QDebug &debug, size_t sizeofT, quint64 value)
Definition qdebug.cpp:1444
Q_CORE_EXPORT void qt_QMetaEnum_flagDebugOperator(QDebug &debug, size_t sizeofT, uint value)
Definition qdebug.cpp:1435
Q_CORE_EXPORT QDebug operator<<(QDebug debug, QDir::Filters filters)
Definition qdir.cpp:2620
#define QT_MESSAGELOG_FUNC
Definition qlogging.h:162
#define QT_MESSAGELOG_FILE
Definition qlogging.h:160
#define QT_MESSAGE_LOGGER_NORETURN
Definition qlogging.h:70
#define QT_MESSAGELOG_LINE
Definition qlogging.h:161
Q_CORE_EXPORT void qSetMessagePattern(const QString &messagePattern)
#define QT_MESSAGELOGCONTEXT
Definition qlogging.h:155
QtMsgType
Definition qlogging.h:30
@ QtCriticalMsg
Definition qlogging.h:34
@ QtFatalMsg
Definition qlogging.h:35
@ QtDebugMsg
Definition qlogging.h:31
Q_CORE_EXPORT void qt_message_output(QtMsgType, const QMessageLogContext &context, const QString &message)
void(* QtMessageHandler)(QtMsgType, const QMessageLogContext &, const QString &)
Definition qlogging.h:197
QMutex QBasicMutex
Definition qmutex.h:360
void setPattern(const QString &pattern)
std::unique_ptr< std::unique_ptr< const char[]>[]> literals
std::chrono::steady_clock::time_point appStartTime
std::unique_ptr< const char *[]> tokens
QList< QString > timeArgs
static QBasicMutex mutex
void setDefaultPattern()
static constexpr bool Value
Definition qdebug.h:687
static constexpr bool Value
Definition qdebug.h:683