Qt 模块中的线程支持

线程和 SQL 模块

A connection can only be used from within the thread that created it. Moving connections between threads or creating queries from a different thread is not supported.

In addition, the third party libraries used by the QSqlDrivers can impose further restrictions on using the SQL Module in a multithreaded program. Consult the manual of your database client for more information

在线程中描绘

QPainter can be used in a thread to paint onto QImage , QPrinter , QPicture , and (for most platforms) QPixmap paint devices. Painting onto QWidgets is not supported. On macOS the automatic progress dialog will not be displayed if you are printing from outside the GUI thread.

Any number of threads can paint at any given time, however only one thread at a time can paint on a given paint device. In other words, two threads can paint at the same time if each paints onto separate QImages, but the two threads cannot paint onto the same QImage at the same time.

线程和富文本处理

The QTextDocument , QTextCursor ,和 所有相关类 are reentrant.

注意, QTextDocument instance created in the GUI thread may contain QPixmap image resources. Use QTextDocument::clone () to create a copy of the document, and pass the copy to another thread for further processing (such as printing).

线程和 SVG 模块

The QSvgGenerator and QSvgRenderer 类在 QtSvg module are reentrant.

线程和隐式共享类

Qt uses an optimization called 隐式共享 for many of its value class, notably QImage and QString . Beginning with Qt 4, implicit shared classes can safely be copied across threads, like any other value classes. They are fully 可重入 . The implicit sharing is really implicit .

In many people's minds, implicit sharing and multithreading are incompatible concepts, because of the way the reference counting is typically done. Qt, however, uses atomic reference counting to ensure the integrity of the shared data, avoiding potential corruption of the reference counter.

Note that atomic reference counting does not guarantee thread-safety . Proper locking should be used when sharing an instance of an implicitly shared class between threads. This is the same requirement placed on all 可重入 classes, shared or not. Atomic reference counting does, however, guarantee that a thread working on its own, local instance of an implicitly shared class is safe. We recommend using 信号和槽 to pass data between threads, as this can be done without the need for any explicit locking.

To sum it up, implicitly shared classes in Qt 4 are really 隐式 shared. Even in multithreaded applications, you can safely use them as if they were plain, non-shared, reentrant value-based classes.

线程和 QObject