可能标题问题不是很明确。我在 Windows7 上使用 Qt5。
在某个线程(QThread)中,在 "process()"
函数/方法中,我必须等待 "encrypted()"
SIGNAL 所属到我在这个线程中使用的 QSslSocket。另外我想我应该使用 QTimer 并等待 "timeout()"
SIGNAL 以避免在无限循环中被阻塞...
我现在拥有的是:
// start processing data
void Worker::process()
{
status = 0;
connect(sslSocket, SIGNAL(encrypted()), this, SLOT(encryptionStarted()));
QTimer timer;
connect(&timer, SIGNAL(timeout()), this, SLOT(timerTimeout()));
timer.start(10000);
while(status == 0)
{
QThread::msleep(5);
}
qDebug("Ok, exited loop!");
// other_things here
// .................
// end other_things
emit finished();
}
// slot (for timer)
void Worker::timerTimeout()
{
status = 1;
}
// slot (for SSL socket encryption ready)
void Worker::encryptionStarted()
{
status = 2;
}
好吧,显然它不起作用。它永远停留在那个while循环中......
所以,问题是:有没有办法解决这个问题?我怎样才能等待那个 "encrypted()"
SIGNAL 但不超过 - 比如说 10 秒 - 为了避免卡在那个等待循环/线程中?
最佳答案
您可以使用本地事件循环来等待信号发出:
QTimer timer;
timer.setSingleShot(true);
QEventLoop loop;
connect( sslSocket, &QSslSocket::encrypted, &loop, &QEventLoop::quit );
connect( &timer, &QTimer::timeout, &loop, &QEventLoop::quit );
timer.start(msTimeout);
loop.exec();
if(timer.isActive())
qDebug("encrypted");
else
qDebug("timeout");
在此等待,直到发出 encrypted
或超时。
关于c++ - Qt5 : How to wait for a signal in a thread?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31358646/