【问题标题】:Qt: Immediately start thread, without delay of main event loopQt:立即启动线程,不延迟主事件循环
【发布时间】:2015-04-26 06:15:10
【问题描述】:

以下成员函数在主事件循环中运行。

    void MyClass::update()
    {
        Data x = m_interpolator->getRequest(m_interpolationRequest)
        // non blocking new calclulation request
        m_interpolator->asyncRequestCalculations(++m_interpolationRequest);
        // I want to run doCalculations from now on in a second thread
        ... updates ... // takes some time
    }
    <-- earliest time when doCalculations() will be triggered

每次调用update 时,我都会请求一个新的计算,我将在下一个周期中获取该计算。

CInterpolator (m_interpolator) 是不同线程中的QObject(使用moveToThread)。 asyncRequestCalculations 调用(非阻塞)CInterpolator::doCalculations 的调用(与向doCalculations 插槽发送信号相同)。

它可以工作,但是太慢了。发生的情况是 doCalculations 的信号已正确调度,但 CInterpolator 仅在 函数 update 之后调用。可以理解,这就是 Qt 事件循环的工作原理。

但对我来说,这浪费了... updates ... 块的时间。我希望计算与... updates ... 并行进行。 我怎样才能做到这一点?

【问题讨论】:

  • 你的意思是当... updates ...还在忙的时候结果就准备好了?
  • 不!但是计算已经可以并行开始,不需要完成。上面更新使其更明显
  • 如果 doCalculations 没有被触发,那么我的猜测是它不是在不同的线程中。你正确地调用 moveToThread 了吗?
  • 是的,在我通过 QASSERT 检查的实际代码中,它正确地具有不同线程的亲和性。我的问题是如何最好地触发第二个线程。我知道信号/插槽是一种方式,但信号只会在更新完成后由主事件循环处理。
  • 显示更多代码!如果您将m_interpolator 正确移动到其他线程(无父线程),则不应直接从主线程调用其方法。您应该使用将进行线程间通信的槽信号机制。使用信号为m_interpolator 安排工作,并使用信号报告这项工作的进度。

标签: c++ qt qthread


【解决方案1】:

主事件循环应该是快速操作,应该连续执行。因此,这就是您观察到应用程序太慢的原因:刷新率低于应有的速度。

不建议在更新/事件循环中使用操作。

顺便说一句,要进行并行执行,您必须使用threads。 一个代码 sn-p 应该是:

void MyClass::update()
    {
        Data x = m_interpolator->getRequest(m_interpolationRequest)
        // non blocking new calclulation request
        m_interpolator->asyncRequestCalculations(++m_interpolationRequest);
        // I want to run doCalculations from now on in a second thread

       std::thread first(update());
    }

【讨论】:

  • 正如我所写,CInterpolator 是驻留在另一个线程 qt-project.org/doc/qt-4.8/qobject.html#moveToThread 中的 QObject,因此它的亲和性是新线程的亲和性。并不是说应用程序没有响应,尤其是因为我已经从主事件循环中取出了计算。只有在计算开始之前的延迟是不可取的。
  • 我已经用线程使用的代码 sn-p 更新了我的答案。更好地将更新封装在一个函数中,该函数将由名为 first 的线程执行
  • 截至编辑:所以您的建议是使用 std::thread 而不是 Qt 的线程机制。是这个主意吗?
  • Qt线程机制也可以使用,没有任何问题。我提供了标准版本,试图提供更通用版本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多