c++ - 让 QtConcurrent 中的 QTimer 正常工作

标签 c++ multithreading qt

我目前正在尝试让 QTimer 工作并在单独的线程中运行时发出适当的信号。我不确定我应该怎么做才能发出 timeout() 信号。

当我尝试使用 QFutureQFutureWatcher 时,它们永远不会抛出它们的 finished() 信号,因为这个线程永远不会真正结束,它只是一直循环。

我已经查看了许多其他问题 1 , 2 , 3 , 4 , 5无济于事。

这是我目前拥有的。任何建议将不胜感激!

Foo.cpp

Foo::Foo() {
    ...
    mcTimerForSpoilers = new QTimer(this);
    connect(mcTimerForSpoilers, SIGNAL(timeout()), this, SLOT(queueDownloadOfSpoilerFile()), Qt::QueuedConnection);
    QtConcurrent::run(this, &Foo::manageSpoilerTimer);
}

void Foo::manageSpoilerTimer() {
    ...
    mcTimerForSpoilers->setInterval(5000); // 5 seconds
    mcTimerForSpoilers->start();
}

void Foo::queueDownloadOfSpoilerFile() {
    ...
    std::cerr << "Queue Download" << std::endl;
    manageSpoilerTimer(); // Restart the timer
}

最佳答案

你的设计是错误的。您调用 QtConcurrent::run(this, &Foo::manageSpoilerTimer);但是计时器只能从它自己的线程启动。

此外,您没有指定时间间隔,因此计时器会持续触发,但每次超时时您也会继续启动计时器。

不清楚你真正想做什么。看起来你不知道自己在做什么。

我不认为 QtConcurrent 是开始下载的好选择。它不支持进度跟踪、暂停或取消,这些都是下载内容应该使用的功能。您应该改为使用基于线程 QObject 的 worker,如 this answer 中所述。 .

关于c++ - 让 QtConcurrent 中的 QTimer 正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44867895/

相关文章:

python - Apache spark 是如何处理 python 多线程问题的?

java - 异步方法调用完成后,Spring 命令行应用程序挂起

c++ - 两个类的前向声明会导致构造函数中的循环依赖吗?

c++ - 在单个 IF 语句中测试多个 boolean 值

c++ - 系统调用 creat 的奇怪行为

c++ - 如何实现编译时检查 CRTP 中的向下转换是否有效?

java - boolean 方法不能返回任何东西

c++ - Qt 将 base64 转换为 QImage 返回 null

c++ - 跨线程的 sigslot 信号

Qt3D 不同 RenderPasses 的不同 Material