Set priority to GUI thread in Qt

John Yang picture John Yang · Sep 25, 2013 · Viewed 8.1k times · Source

Is it possible to set priority to the main GUI thread so it has higher priority comparing to the other threads (QThread)?

My aim is to not to freeze up the GUI while the other threads are doing some intensive computation which may occupy CPU to 100% load. It would be great if someone can share a way to make sure GUI will not freeze during this period while the other computation threads can still try to maximize the CPU usage.

I thought about managing other threads, so I don't start too many computation threads at the same time.

Answer

Change the priority of the current thread when the current thread is the gui thread:

int main(int argc, char ** argv) {
  QApplication app(argc, argv);
  QThread::currentThread()->setPriority(QThread::HighPriority);
  ...
}

You can submit the change from any other thread, too – as long as the main (GUI) thread has a running event loop:

QMetaObject::invokeMethod(qApp, []{
  QThread::currentThread()->setPriority(QThread::HighPriority);
});