等待一个SLOT用Qt完成执行
Wait for a SLOT to finish the execution with Qt
在我的代码中,我发出了一个信号 (mySignal),我想等待连接的插槽 (mySlot) 执行结束,然后再继续:
emit mySignal();
// Wait for the end of mySlot execution...
// Some code that has to be executed only after the end of mySlot execution...
有办法吗?
如果发送者和接收者在同一个线程中使用Qt::DirectConnection
,如果他们在2个不同的线程中使用Qt::BlockingQueuedConnection
.
ClassA a;
ClassB b;
ClassC c;
c.moveToThread(aThread);
QObject::connect(&a, &ClassA::signal, &b, &ClassB::slot, Qt::DirectConnection);
QObject::connect(&a, &ClassA::signal, &c, &ClassC::slot, Qt::BlockingQueuedConnection);
请注意,如果出现以下情况,您将必须 disconnect/reconnect:
- 发送者和接收者结束于同一个线程,而他们以前不是,否则你将陷入死锁。
- 发送者或接收者最终处于 2 个不同的线程中,而他们之前处于同一线程中。
如果发送方和接收方在同一个线程中,则 Qt::DirectConnection
也是默认设置(参见 Qt::AutoConnection)。
在我的代码中,我发出了一个信号 (mySignal),我想等待连接的插槽 (mySlot) 执行结束,然后再继续:
emit mySignal();
// Wait for the end of mySlot execution...
// Some code that has to be executed only after the end of mySlot execution...
有办法吗?
如果发送者和接收者在同一个线程中使用Qt::DirectConnection
,如果他们在2个不同的线程中使用Qt::BlockingQueuedConnection
.
ClassA a;
ClassB b;
ClassC c;
c.moveToThread(aThread);
QObject::connect(&a, &ClassA::signal, &b, &ClassB::slot, Qt::DirectConnection);
QObject::connect(&a, &ClassA::signal, &c, &ClassC::slot, Qt::BlockingQueuedConnection);
请注意,如果出现以下情况,您将必须 disconnect/reconnect:
- 发送者和接收者结束于同一个线程,而他们以前不是,否则你将陷入死锁。
- 发送者或接收者最终处于 2 个不同的线程中,而他们之前处于同一线程中。
如果发送方和接收方在同一个线程中,则 Qt::DirectConnection
也是默认设置(参见 Qt::AutoConnection)。