Thread Support in Qt 4

Qt 4 makes it easier than ever to write multithreaded applications. More classes have been made usable from non-GUI threads, and the signals and slots mechanism can now be used to communicate between threads.

一般概述

QThread now inherits QObject 。它发射指示线程启动 (或执行完成) 的信号,且还提供了几个槽。

Each thread can now have its own event loop. The initial thread starts its event loops using QCoreApplication::exec (); other threads can start an event loop using QThread::exec ()。像 QCoreApplication , QThread also provides an exit (int) 函数和 quit() 槽。

线程中的事件循环使之可能对要使用某些非 GUI Qt 类的线程,要求存在事件循环 (譬如 QTimer , QTcpSocket ,和 QProcess ). It also makes it possible to connect signals from any threads to slots of a specific thread. When a signal is emitted, the slot isn't called immediately; instead, it is invoked when control returns to the event loop of the thread to which the object belongs. The slot is executed in the thread where the receiver object lives. See signals-and-slots-across-threads and QObject::connect () 了解细节。

Qt 4 also introduces a new synchronization class: QReadWriteLock 。类似于 QMutex , except that it distinguishes between "read" and "write" access to shared data and allows multiple readers to access the data simultaneously. Using QReadWriteLock 而不是 QMutex when it is possible can make multithreaded programs more concurrent.

Since Qt 4, 隐式共享 classes can safely be copied across threads, like any other value classes. They are fully reentrant. This is implemented using atomic reference counting operations, which are implemented in assembly language for the different platforms supported by Qt. Atomic reference counting is very fast, much faster than using a mutex.

Qt 中的线程支持 了解更多信息。

Comparison with Qt 3

Earlier versions of Qt offered an option to build the library without thread support. In Qt 4, threads are always enabled.

Qt 3 had a class called QDeepCopy that you could use to take a deep copy of an implicitly shared object. In Qt 4, the atomic reference counting makes this class superfluous.