18

What are the differences between QThreads and QRunnable ?

When should I use QThread and when QRunnable ?

sandwood
  • 2,038
  • 20
  • 38
CDT
  • 10,165
  • 18
  • 66
  • 97
  • 1
    A very good talk about multithreading in Qt (they explain QThread, QRunnable, QThreadPool, cross-threads signal-slots, etc.) was given at Qt DevDays 2011. Videos can be found here: [Part 1](http://qt-project.org/videos/watch/advanced-qt-a-deep-dive-3-6-multithreading-1), [Part 2](http://qt-project.org/videos/watch/advanced-qt-a-deep-dive-4-6-multithreading-2). – leemes May 28 '13 at 12:24
  • 2
    @leemes the link targets are gone :( – d.Candela Oct 11 '19 at 14:24

3 Answers3

14

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.

10

The QRunnable class and the QtConcurrent::run() function are well suited to situations where we want to perform some background processing in one or more secondary threads without needing the full power and flexibility provided by QThread.

from "Advanced Qt Programming: Creating Great Software with C++ and Qt 4" by Mark Summerfield

Erik Kaju
  • 3,147
  • 3
  • 19
  • 28
  • 17
    This answer would be useful if it explained "full power and flexibility provided by QThread", because it suggests you should default to using QRunnable, and use QThread only when you need... What? Signals? An event loop? Etc. – Oliver Dec 02 '16 at 03:47
2

Choosing between using QThreadPool and QThread
The Qt framework offers many tools for multithreading. Picking the right tool can be challenging at first, but in fact, the decision tree consists of just two options: you either want Qt to manage the threads for you, or you want to manage the threads by yourself. However, there are other important criteria:

Tasks that don’t need the event loop. Specifically, the tasks that are not using signal/slot mechanism during the task execution. Use: QtConcurrent and QThreadPool + QRunnable.

Tasks that use signal/slots and therefore need the event loop. Use: Worker objects moved to + QThread.

Refer the link for detailed description: nice read on qt threading

Jack
  • 694
  • 8
  • 20