Qt:立即启动线程,不延迟主事件循环

Qt: Immediately start thread, without delay of main event loop

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

    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 ... 并行进行。 我怎样才能做到这一点?

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

不建议在update/event循环中使用操作。

顺便说一句,为了并行执行,您必须使用 threads。 一个代码 snippet 应该是:

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());
    }