Search code examples
c++qtqthread

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


The following member function runs in the 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

With each call of update I request a new calculation, which I will fetch in the next cycle.

CInterpolator (m_interpolator) is a QObject in a different thread (using moveToThread). asyncRequestCalculations invokes (non-blocking) a call of CInterpolator::doCalculations (same as sending a signal to the doCalculations slot).

It works, but is too slow. What happens is that the signal for doCalculations is properly scheduled, but CInterpolator only called after function update has been left. Understandable, this is how the Qt event loop works.

But for me it wastes the time of the ... updates ... block. I want the calculation taking place in parallel to ... updates .... How could I accomplish this?


Solution

  • Main event loops are supposed to be fast operations, which should be executed continuously. Therefore, that is why you observe that the application is too slow: the refresh rate is slower than it should be.

    It is not recommended to use slow operations in update/event loop.

    By the way, in order to have parallel execution, you would have to use threads. One code snippet should be:

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