Qt 4.5 - Is emitting signal a function call, or a

2019-03-09 00:30发布

I am not sure about the nature of the signal/slot mechanism in Qt 4.5. When a signal is emitted, is it a blocking function call or a thread? Say this

emit GrabLatestData();

// proceed with latest data

Will all the signal/slot chain be resolved before proceeding to the next line?

标签: qt qt4
3条回答
家丑人穷心不美
2楼-- · 2019-03-09 00:40

It depends. From the documentation:

When a signal is emitted, the slots connected to it are usually executed immediately, just like a normal function call. When this happens, the signals and slots mechanism is totally independent of any GUI event loop. Execution of the code following the emit statement will occur once all slots have returned. The situation is slightly different when using queued connections; in such a case, the code following the emit keyword will continue immediately, and the slots will be executed later.

So in normal cases, it will be synchronous and blocking, and with queued connections it will be asynchronous and non-blocking.

查看更多
Melony?
3楼-- · 2019-03-09 00:59

laalto's answer above is correct. One further point though: if all of your QObjects belong to the same thread and you haven't manually specified queued connections, then the execution of slots connected to the signal occurs synchronously - all processing will be done before the next line after the 'emit' statement. Since this is the most common case, the answer to your question is normally 'yes'.

The documentation on signals and slots across multiple threads may be helpful to you.

查看更多
女痞
4楼-- · 2019-03-09 01:01

The biggest problem is that you just can't know. That is, if you're looking from the class's point of view. When you emit, you don't know what will happen:

  • If no one is connected to the signal, nothing happens
  • If someone from the same thread is connected using any type except Qt::QueuedConnection, the call will be blocking
  • If someone from the same thread is connected using Qt::QueuedConnection, the call will be non-blocking
  • If someone from a different thread is connected using Qt::DirectConnection (be very careful when you do that!) or Qt::BlockingQueuedConnection, the call will be blocking
  • If someone from a different thread is connected using Qt::AutoConnection or Qt::QueuedConnection, the call will be non-blocking

It gets even more difficult to know what will happen if multiple objects are connected to the signal. In that case some slots might have run while others are still queued. There is, by the way, no thread involved with a non-blocking connect. There's only an event that gets posted in the event loop of the thread of the receiving object.

查看更多
登录 后发表回答