Unsolved How the signal/slot works for slot doing time consuming operation?
-
How the signal/slot works for slot doing time consuming operation?
Assume,
void Widget::slot(int value)
{
for(int x = 0; x < 10000 ;++x)
qDebug() << value;
}connect(widget, SIGNAL(signal(int)),
widget, SLOT(slot(int)));void Widget::on_pushButton_clicked()
{
for(int i = 0; i < 100; ++i)
emit signal(i);
}Here the signal is emitted 100 times, each time slot performs time consuming operation.
Does the second signal is emitted after the slot for first signal emission is completed?
How to handle these kind of scenarios in realtime.
-
You should read the Signals & slots documentation. It gives a detailed description, but here's the short version:
Does the second signal is emitted after the slot for first signal emission is completed?
In the simple case that the sender and receiver live in the same thread and you don't pass any extra parameters to the
connect
statement - yes, slot connected to a signal will be invoked immediately, so the execution order in your example will besignal(0); slot(0); signal(1); slot(1); signal(2); slot(2); ...
If you create a queued connection by passing an extra
Qt::QueuedConnection
param to theconnect
statement the invocation of the slot is deferred until the control flow in the thread the receiver lives in gets back to the event loop. In your example, if you'd change theconnect
statement toconnect(widget, SIGNAL(signal(int)), widget, SLOT(slot(int)), Qt::QueuedConnection);
The execution order would be
signal(0); signal(1); signal(2); ... // here you exit on_pushButton_clicked() so the control goes back to event loop slot(0); slot(1); slot(2); ...
In a multithreaded app things get a little trickier. If sender and receiver live in different threads the slot invocation is queued in the receiver's thread and so the only thing you can tell about when it will be executed is after the signal emission.
For example if you had two objects and a connect like this:connect(widget, SIGNAL(signal(int)), some_object_in_another_thread, SLOT(slot(int)));
The execution order might look something like this:
THREAD1 THREAD2 signal(0); signal(1); signal(2); slot(0); ... slot(1); slot(2); ...
You can't rely on the signal/slot order in that case.