c++ - QTimer->remainingTime() 返回 -1371648957

标签 c++ multithreading qt qtimer qeventloop

当我使用 Qt 5.3.2 运行以下代码时,剩余时间设置为 -1371648957。

QTimer *timer = new QTimer(this);
timer->setSingleShot(true);
timer->start(100);
qDebug() << "remaining" << timer->remainingTime();

如果我之后继续在循环中打印剩余时间,负值只会增加,因此永远不会触发 timeout()。这对我来说真的毫无意义。

为了提供一点上下文,这段代码在一个单独的线程中运行,并且 QTimer 不是在线程对象的构造函数中创建的。

这里是一些更新的代码,使事情更清楚。

void MainObject::SomeMethod(){
    // main thread
    ObjectWithTimer *owt = new ObjectWithTimer();    
    QThread *someThread = new QThread();
    owt->moveToThread(someThread);
    connect(someThread, SIGNAL(started()), owt, SLOT(doStuff()));
    someThread->start();
}

void ObjectWithTimer::doStuff(){
    while(condition){
        // do various stuff
        // among other things emit SIGNALS to the main thread, that are received
        // so the event loop in the thread is running
        QTimer *timer = new QTimer(this);
        timer->setSingleShot(true);
        timer->start(100);
        qDebug() << "remaining" << timer->remainingTime();

        connect(timer, SIGNAL(timeout()), this, SLOT(onClientTimeoutTest()));
    }
}
void ObjectWithTimer::onClientTimeoutTest(){
    // this method is of course never fired, since the remaining time never reaches 0
}

我已经检查了计时器创建是否在单独的线程中正确运行,并且线程内的 Qts 事件循环是否正常工作,因为我可以发出主线程接收的信号。

如果我这样设置定时器也没有区别

timer->setSingleShot(true);
timer->setInterval(100);
timer->start();

如果我将秒数更改为 100000 或 0,则剩余时间只会略微更改为 -1374002988,当我重新启动应用程序时它仍然会更改,但长度保持不变。

我还检查了 timer->remainingTime() 行上的调试器,内部 inter 变量正确设置为 100。

这可能是内存地址或类似的东西吗?

最佳答案

QTimer *timer = new QTimer(this);
timer->setSingleShot(true);
timer->start(100);
qDebug() << "remaining" << timer->remainingTime();

由于 QTimer 在事件循环上工作,我怀疑此时调用 remainingTime 可能返回无效,因为 Timer 尚未完全初始化。

如果你关注 QTimer 的源代码,你会发现它实际上使用了 QObject 的定时器并调用了 QObject::startTimer。 source for QObject (第 1632 行)显示此时已调度事件:-

return d->threadData->eventDispatcher->registerTimer(interval, this);

因此,允许代码在调用 start 之后和请求剩余时间之前返回到主事件循环。

关于c++ - QTimer->remainingTime() 返回 -1371648957,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28563004/

相关文章:

c++ - Qt 声子视频播放器示例 C++ 或 python

c++ - 如何从开始在对象的成员函数中执行的 c++ boost thread_group 创建新线程?

multithreading - 是否可以将互斥对象的引用传递到新线程中?我们是否总是需要使用move来关闭? [复制]

c++ - 在简单的图形编辑器中绘制 "preview"行

c++ - Arduino 串行监视器上的垃圾。如何解决?

c++ - 重新定义公共(public)/私有(private)接口(interface)的枚举

multithreading - 您可以在Clojure中使用 `send`和 `send-off`混合代理 Action 提交吗?应该发生什么?

c++ - 创建 QGradient

c++ - 如何高效地移动大量qgraphicsitem?

c++ - 为什么 C++ lambda 不支持 move 捕获?