Probably the title question is not very explicit. I am using Qt5 on Windows7.
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;
}
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");
Here it waits until encrypted
is emitted or the the timeout reaches.