Qt跨線程信號和槽的連接


Qt支持三種類型的信號-槽連接:
1,直接連接,當signal發射時,slot立即調用。此slot在發射signal的那個線程中被執行(不一定是接收對象生存的那個線程)  
2,隊列連接,當控制權回到對象屬於的那個線程的事件循環時,slot被調用。此slot在接收對象生存的那個線程中被執行
3,自動連接(缺省),假如信號發射與接收者在同一個線程中,其行為如直接連接,否則,其行為如隊列連接。

連接類型可能通過以向connect()傳遞參數來指定。注意的是,當發送者與接收者生存在不同的線程中,而事件循環正運行於接收者的線程中,使用直接連接是不安全的。同樣的道理,調用生存在不同的線程中的對象的函數也是不是安全的。QObject::connect()本身是線程安全的。

 

 

This enum describes the types of connection that can be used between signals and slots. In particular, it determines whether a particular signal is delivered to a slot immediately or queued for delivery at a later time.

Constant Value Description
Qt::AutoConnection 0 (default) If the signal is emitted from a different thread than the receiving object, the signal is queued, behaving as Qt::QueuedConnection. Otherwise, the slot is invoked directly, behaving as Qt::DirectConnection. The type of connection is determined when the signal is emitted.
Qt::DirectConnection 1 The slot is invoked immediately, when the signal is emitted.
Qt::QueuedConnection 2 The slot is invoked when control returns to the event loop of the receiver's thread. The slot is executed in the receiver's thread.
Qt::BlockingQueuedConnection 4 Same as QueuedConnection, except the current thread blocks until the slot returns. This connection type should only be used where the emitter and receiver are in different threads. Note: Violating this rule can cause your application to deadlock.
Qt::UniqueConnection 0x80 Same as AutoConnection, but the connection is made only if it does not duplicate an existing connection. i.e., if the same signal is already connected to the same slot for the same pair of objects, then the connection will fail. This connection type was introduced in Qt 4.6.
Qt::AutoCompatConnection 3 The default type when Qt 3 support is enabled. Same as AutoConnection but will also cause warnings to be output in certain situations. See Compatibility Signals and Slots for further information.

With queued connections, the parameters must be of types that are known to Qt's meta-object system, because Qt needs to copy the arguments to store them in an event behind the scenes. If you try to use a queued connection and get the error message:

 QObject::connect: Cannot queue arguments of type 'MyType'

Call qRegisterMetaType() to register the data type before you establish the connection.

When using signals and slots with multiple threads, see Signals and Slots Across Threads.

See also Thread Support in QtQObject::connect(), and qRegisterMetaType().

http://blog.csdn.net/seanyxie/article/details/7025183


qDebug()<<"from thread slot_main:" <<currentThreadId(); 打印當前threadID


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM