Qt5 Tutorial QThreads - Priority - 2020
In this tutorial, we will learn how a thread behaves depending on its priority.
Most of the codes are the same as in the QThreads - Creating Threads except the portion that sets the thread priority.
The priority is set by the parameter passed into the start() method:
Its definition looks like this:
void QThread::start(Priority priority = InheritPriority)
The start() begins execution of the thread by calling run().
The operating system will schedule the thread according to the priority parameter. If the thread is already running, this function does nothing.
The effect of the priority parameter is dependent on the operating system's scheduling policy. In particular, the priority will be ignored on systems that do not support thread priorities.
enum QThread::Priority
Constant | Value | Description |
---|---|---|
QThread::IdlePriority | 0 | scheduled only when no other threads are running. |
QThread::LowestPriority | 1 | scheduled less often than LowPriority. |
QThread::NormalPriority | 3 | the default priority of the operating system. |
QThread::HighestPriority | 5 | scheduled more often than HighPriority. |
QThread::QThread::InheritPriority | 7 | use the same priority as the creating thread. This is the default. |
Let's look at changes made in main.cpp:
#include <QCoreApplication> #include "mythread.h" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); MyThread thread1("A"), thread2("B"), thread3("C"); thread1.start(QThread::LowestPriority); thread2.start(); thread3.start(QThread::HighestPriority); return a.exec(); }
The scheduler on my system seems respect the thread priority. The lowly "A" thread finished last!
... "A" 77 "A" 78 "A" 79 "A" 80 "A" 81 "A" 82 "A" 83 "A" 84 "A" 85 "A" 86 "A" 87 "A" 88 "A" 89 "A" 90 "A" 91 "A" 92 "A" 93 "A" 94 "A" 95 "A" 96 "A" 97 "A" 98 "A" 99 "A" 100
There could be a priority inversion issue. Please visit for more on Priority Inversion.
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization