QThread Class
The QThread class provides a platform-independent way to manage threads. More…
| Header | #include <QThread> |
|---|---|
| CMake | target_link_libraries(app PRIVATE Nt::Core) |
| Module | Nt Core C++ Classes |
| Inherits | QObject |
List of all members, including inherited members
Public Types
| enum | Priority |
Public Functions
| QThread(QObject *parent = nullptr) | |
| ~QThread() | |
| bool | isCurrentThread() const |
| void | setPriority(Priority priority) |
| Priority | priority() const |
| bool | isFinished() const |
| bool | isRunning() const |
| void | requestInterruption() |
| bool | isInterruptionRequested() const |
| void | setStackSize(uint stackSize) |
| uint | stackSize() const |
| int | loopLevel() const |
| QAbstractEventDispatcher * | eventDispatcher() const |
| bool | wait(QDeadlineTimer deadline = QDeadlineTimer(QDeadlineTimer::Forever)) |
| bool | wait(unsigned long time) |
Public Slots
Signals
Static Public Members
| Qt::HANDLE | currentThreadId() |
| QThread * | currentThread() |
| int | idealThreadCount() |
| void | yieldCurrentThread() |
| bool | isMainThread() |
| QThread * | create(Function &&f, Args &&...args) |
| void | sleep(unsigned long secs) |
| void | msleep(unsigned long msecs) |
| void | usleep(unsigned long usecs) |
| void | sleep(std::chrono::nanoseconds nsecs) |
Protected Functions
Detailed Description
A QThread object manages one thread of control. By default the thread runs an event loop from run(), so objects that were moved to it with QObject::moveToThread() receive timers, posted events and queued signals there:
QThread thread;
auto *worker = new Worker;
worker->moveToThread(&thread);
QObject::connect(&thread, &QThread::finished, worker, &QObject::deleteLater);
QObject::connect(&producer, &Producer::ready, worker, &Worker::process);
thread.start();
// ...
thread.quit();
thread.wait();
Reimplement run() instead to run your own code in the thread, or use create() to run a function. The thread that creates a QThread owns the object, and the object lives in the creating thread, not in the thread it manages. Destroying a QThread that is still running prints a message and aborts the process, as in Qt.
Every thread has a QThread object. Threads that were not started by QThread, such as the main thread, get one when they first use Nt; currentThread() returns it.
See also QObject::moveToThread(), QThreadPool, QThreadStorage, Thread Support in Nt and Signals and Slots.
Differences from Qt
There is no terminate() or setTerminationEnabled(), and no setEventDispatcher(): the dispatcher of a thread cannot be replaced, and eventDispatcher() returns a handle onto it even before the thread has started. Priorities are stored and returned by priority(), but are applied only for IdlePriority (as SCHED_IDLE) and, if the process has a real-time scheduling policy, as a scaled real-time priority. The started() and finished() signals have no QPrivateSignal argument, and an adopted thread does not emit finished(). A thread that has finished keeps its objects, timers and posted events; they run again if the thread is restarted. currentThreadId() is the pthread_t cast to a pointer.
On Zephyr the stack of a thread has CONFIG_NT_THREAD_STACK_SIZE bytes, taken from the kernel heap, unless setStackSize() asked for another size, and idealThreadCount() is 1. The C++ library there has no thread support, so objects that are shared between threads are not safe yet; talk to a thread with queued signals. See Nt on Zephyr.
Member Type Documentation
enum QThread::Priority
This enum describes how the operating system should schedule a thread.
| Constant | Description |
|---|---|
QThread::IdlePriority | Runs only when no other thread is runnable (SCHED_IDLE on Linux). |
QThread::LowestPriority | Stored and returned by priority(); the scheduler of a normal Linux process ignores it. |
QThread::LowPriority | Stored and returned by priority(); the scheduler of a normal Linux process ignores it. |
QThread::NormalPriority | The default scheduling of the system. |
QThread::HighPriority | Stored and returned by priority(); the scheduler of a normal Linux process ignores it. |
QThread::HighestPriority | Stored and returned by priority(); the scheduler of a normal Linux process ignores it. |
QThread::TimeCriticalPriority | Stored and returned by priority(); the scheduler of a normal Linux process ignores it. |
QThread::InheritPriority | The thread gets the priority of the thread that called start(). |
Member Function Documentation
QThread::QThread(QObject *parent = nullptr)
Constructs a thread object with the given parent. The thread is not started; call start().
QThread::~QThread()
Destroys the thread object. If the thread is still running, this prints a message and aborts the process, so call quit() or exit() and wait() first. A thread that is in the middle of finishing is waited for.
template <typename Function, typename... Args> QThread * QThread::create(Function &&f, Args &&...args)
Creates a thread that calls f with args, copied into the thread, instead of running an event loop, and returns it. The thread is not started. The caller owns it and can connect finished() to deleteLater().
See also start().
QThread * QThread::currentThread()
Returns the QThread object that stands for the calling thread. For a thread that was not started by QThread, the object is created the first time the thread uses Nt.
See also currentThreadId() and isMainThread().
Qt::HANDLE QThread::currentThreadId()
Returns the thread handle of the calling thread, an opaque value that identifies the thread. On Linux it is the pthread_t.
See also currentThread().
QAbstractEventDispatcher * QThread::eventDispatcher() const
Returns the event dispatcher of the thread. It is created on first use and lives as long as the thread data does, so it can be asked for before the thread is started.
This function was introduced in 6.0.
See also QAbstractEventDispatcher::instance().
int QThread::exec()
Enters the thread's event loop and waits until exit() or quit() is called, then returns the code passed to exit(). If exit() was called before exec(), it returns at once. Call it from run() only.
See also quit(), exit() and loopLevel().
void QThread::exit(int retcode = 0)
Tells the thread's event loops to exit with the return code retcode, so that exec() returns it. After that run() usually returns and the thread finishes. Does nothing if the thread is not running. A call that arrives before the thread has entered exec() makes exec() return at once, so it is safe to call right after start().
void QThread::finished()
This signal is emitted from the thread when it is about to finish, after run() has returned. Objects that live in the thread and were scheduled with deleteLater() are deleted right after it. Connect it to deleteLater() of the QThread to delete the thread object when it ends.
See also started() and isFinished().
int QThread::idealThreadCount()
Returns the number of threads the machine can run at the same time: the number of processors the process may use. Returns 1 if that cannot be determined.
bool QThread::isCurrentThread() const
Returns true if this object stands for the calling thread; otherwise returns false.
This function was introduced in 6.8.
See also currentThread().
bool QThread::isFinished() const
Returns true if the thread has finished, that is, it ran and has completed. A thread that was never started, and a thread that is running, is not finished.
See also isRunning().
bool QThread::isInterruptionRequested() const
Returns true if requestInterruption() was called for this thread since it started. Long-running code in the thread should poll this and return soon after it becomes true.
See also requestInterruption().
bool QThread::isMainThread()
Returns true if the calling thread is the main thread: the thread of the QCoreApplication object, or, without one, the first thread that used Nt.
This function was introduced in 6.4.
bool QThread::isRunning() const
Returns true if the thread is running, including while it is finishing.
See also isFinished().
int QThread::loopLevel() const
Returns the number of event loops that are running in the thread, counting nested ones. It is 0 when the thread is not in an event loop.
See also exec() and QEventLoop::exec().
void QThread::msleep(unsigned long msecs)
Blocks the calling thread for msecs milliseconds.
See also sleep() and usleep().
Priority QThread::priority() const
Returns the priority the thread was started with or last given by setPriority(), which is InheritPriority for a thread that was started without one.
See also setPriority() and start().
void QThread::quit()
Tells the thread's event loop to exit with return code 0. This is the same as calling exit(0).
See also exit().
void QThread::requestInterruption()
Requests that the thread stop what it is doing. Nothing happens unless the thread's code polls isInterruptionRequested() and returns. The request is cleared when the thread is started again. It is safe to call from any thread.
See also isInterruptionRequested().
void QThread::run()
The starting point of the thread. After start() calls it, the thread runs exec() and so handles the events of the objects that live in it. Reimplement it to run other code; when it returns, the thread ends.
void QThread::setPriority(Priority priority)
Sets the priority of the running thread to priority. It does nothing and prints a warning if the thread is not running, and InheritPriority is ignored.
See also priority() and start().
void QThread::setStackSize(uint stackSize)
Sets the maximum stack size of the thread to stackSize bytes, if that is not 0. The size is used the next time the thread is started; a running thread is not affected. A value below the system minimum is raised to it.
See also stackSize().
void QThread::sleep(unsigned long secs)
Blocks the calling thread for secs seconds.
See also msleep() and usleep().
void QThread::sleep(std::chrono::nanoseconds nsecs)
This is an overloaded function.
Blocks the calling thread for nsecs nanoseconds.
This function was introduced in 6.6.
uint QThread::stackSize() const
Returns the stack size set with setStackSize(), or 0 for the system default.
See also setStackSize().
void QThread::start(Priority priority = InheritPriority)
Begins execution of the thread by calling run(), with the given priority, which defaults to inheriting the priority of the creating thread. The started() signal is emitted from the new thread first. Does nothing if the thread is already running. A thread that has finished can be started again.
See also run(), wait() and setPriority().
void QThread::started()
This signal is emitted from the new thread when it starts executing, before run() is called. Slots in objects that live in other threads are called through their event loop.
See also finished() and start().
void QThread::usleep(unsigned long usecs)
Blocks the calling thread for usecs microseconds.
See also sleep() and msleep().
bool QThread::wait(QDeadlineTimer deadline = QDeadlineTimer(QDeadlineTimer::Forever))
Blocks the calling thread until the thread has finished, or until deadline has passed. Returns true if the thread finished or was never started, and false if the deadline expired. Returns false at once, with a warning, if a thread waits for itself. A thread that has finished has already emitted finished() when this returns.
See also isFinished() and start().
bool QThread::wait(unsigned long time)
This is an overloaded function.
Waits for at most time milliseconds. A value of ULONG_MAX waits until the thread finishes.
void QThread::yieldCurrentThread()
Yields execution of the current thread to another runnable thread, if any.