Qt:向 dead/stopped 线程发送信号
Qt: Sending signal to dead/stopped thread
我遇到了这个问题,我可能正在从一个 QThread
向另一个发送信号,但是我无法检查执行 slot
的线程是否是 运行。使用 Qt::QueuedConnection
时框架将如何处理这种情况?
...
WorkerImp* pWorker = new WorkerImp();
QThread worker;
pWorker->moveToThread(&worker);
QObject::connect(&worker, QThread::finished, pWorker, &QObject::deleteLater, Qt::QueuedConnection);
bool connected = QObject::connect(this, &SlaveMaster::requireWork, pWorker, &WorkerImp::doWork, Qt::QueuedConnection);
assert(connected);
// at this point we have connected the signal, thread is not starded.
// however the object that we use to connect still exists and will after we exit the thread.
worker.start();
worker.exit();
worker.wait();
// note that when we exit the QThread we do not destroy the object - it can be start over
emit requireWork();
...
信号从未被处理过。跨线程的排队连接作为事件发布到线程,由其事件循环处理。如果线程停止(因此它的事件循环),则没有人拾取事件并传递它:
来自 Qt 文档 Signals and Slots Across Threads:
Queued Connection: 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.
[...] If no event loop is running, events won't be delivered to the object.
请注意,阻塞排队的连接会死锁
我遇到了这个问题,我可能正在从一个 QThread
向另一个发送信号,但是我无法检查执行 slot
的线程是否是 运行。使用 Qt::QueuedConnection
时框架将如何处理这种情况?
...
WorkerImp* pWorker = new WorkerImp();
QThread worker;
pWorker->moveToThread(&worker);
QObject::connect(&worker, QThread::finished, pWorker, &QObject::deleteLater, Qt::QueuedConnection);
bool connected = QObject::connect(this, &SlaveMaster::requireWork, pWorker, &WorkerImp::doWork, Qt::QueuedConnection);
assert(connected);
// at this point we have connected the signal, thread is not starded.
// however the object that we use to connect still exists and will after we exit the thread.
worker.start();
worker.exit();
worker.wait();
// note that when we exit the QThread we do not destroy the object - it can be start over
emit requireWork();
...
信号从未被处理过。跨线程的排队连接作为事件发布到线程,由其事件循环处理。如果线程停止(因此它的事件循环),则没有人拾取事件并传递它:
来自 Qt 文档 Signals and Slots Across Threads:
Queued Connection: 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.
[...] If no event loop is running, events won't be delivered to the object.
请注意,阻塞排队的连接会死锁