Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++/Qt - QThread vs QRunnable

What are the differences between QThreads and QRunnable ?

When should I use QThread and when QRunnable ?

like image 954
CDT Avatar asked May 28 '13 12:05

CDT


People also ask

Is Qt multithreaded?

Qt offers many classes and functions for working with threads. Below are four different approaches that Qt programmers can use to implement multithreaded applications.

How do you use QThread?

To use it, prepare a QObject subclass with all your desired functionality in it. Then create a new QThread instance, push the QObject onto it using moveToThread(QThread*) of the QObject instance and call start() on the QThread instance. That's all.

What is thread in Qt?

A QThread object manages one thread of control within the program. QThreads begin executing in run(). By default, run() starts the event loop by calling exec() and runs a Qt event loop inside the thread. You can use worker objects by moving them to the thread using QObject::moveToThread().


1 Answers

QThread can run an event loop, QRunnable doesn't have one so don't use it for tasks designed to have an event loop. Also, not being a QObject, QRunnable has no built-in means of explicitly communicating something to other components; you have to code that by hand, using low-level threading primitives (like a mutex-guarded queue for collecting results, etc.). Using QThread you can use signals and slots which are thread safe.

like image 71
Alexandra Anghelescu Avatar answered Sep 18 '22 20:09

Alexandra Anghelescu