17.2.  QThread and QtConcurrent

[ fromfile: threads.xml id: threads ]

Before Qt, cross-platform threads were not generally available for C++ open source developers because threads were relatively new concepts and were handled differently in each operating system. Threads are now found in most operating systems and many modern programming languages. Multicore processors have also become quite common, so threads from the same process can be scheduled to run on different cores by modern operating systems.

Qt's thread model permits the prioritizing and control of threads. QThread provides a low-level class that can be used for explicit creation of long-running threads.

QtConcurrent is a namespace that provides higher-level classes and algorithms for writing concurrent software. One important class in this namespace is QThreadPool, a class that manages a pool of threads. Every Qt application has a QThreadPool::globalInstance() with a suggested maximum thread count that defaults, on most systems, to the number of cores.

Using QtConcurrent's functional map/filter/reduce algorithms, which apply functions in parallel to each item in a container, you can write a program that automatically takes advantage of the system's multiple cores by distributing the processing across the threads managed by the thread pool. Alternatively, you can use QRunnable as a base class for the Command pattern and schedule work with QtConcurrent::run(). In these cases, you do not need to create threads explicitly or manage them directly – you can simply describe the pieces of work as objects with the right interface.

[Important] Why Use Threads?

Sometimes, complexity added to software from using threads can outweigh the performance benefits. If a program is bound by the I/O, chances are that distributing the CPU's work across multiple threads will not show noticeable improvement in the program's overall performance. If, however, there is a significant amount of advance calculation that can be done, and you have idle cores, threads can improve performance.



[104] Introduced in Qt 4.6