c++ - Qt5 : How to wait for a signal in a thread?

标签 c++ multithreading qt timer wait

可能标题问题不是很明确。我在 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/

相关文章:

c++ - 捕捉 QTableWidgetItem 检查状态变化

c++ - 在 .pro 文件 QT 中定义带有转义字符的字符串宏

c++ - 将非引用作为引用传递,没有临时变量

c++ - 模板类的组成

c - pthread_detach 问题

python 3.5 - asyncio - 运行并发连接池

c++ - Ncurses 和 Qt 互操作性

c++ - 在 Qt 中禁用 setGraphicsEffect 继承

c++ - 为什么 Debug 构建失败而 Release 构建成功?

c - 通知多个线程同时开始工作