Qt5:如何等待线程中的信号? [英] Qt5: How to wait for a signal in a thread?
问题描述
标题问题可能不是很明确.我正在Windows7上使用Qt5.
Probably the title question is not very explicit. I am using Qt5 on Windows7.
在某个线程(QThread)中的某个位置,在"process()"
函数/方法中,我必须等待属于我在此线程中使用的QSslSocket的"encrypted()"
信号.另外我想我应该使用QTimer并等待"timeout()"
SIGNAL,以避免在无限循环中被阻塞...
我现在拥有的是:
In a thread (QThread) at some point, in the "process()"
function/method, I must wait for the "encrypted()"
SIGNAL belonging to a QSslSocket I am using in this thread. Also I suppose I should use a QTimer and wait for a "timeout()"
SIGNAL in order to avoid getting blocked in an infinite loop...
What I have now is:
// 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()"
信号,但不能超过-假设是10秒-以避免卡在该等待循环/线程中?
Well, obviously it doesn't work. It stays in that while-loop forever...
So, the question is: Is there a way to solve this problem? How can I wait for that "encrypted()"
SIGNAL but not more than - let's say 10 seconds - in order to avoid getting stuck in that waiting-loop/thread?
推荐答案
您可以使用本地事件循环来等待信号被发出:
You can use a local event loop to wait for the signal to be emitted :
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
或超时.
Here it waits until encrypted
is emitted or the the timeout reaches.
这篇关于Qt5:如何等待线程中的信号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!