2015-02-24 133 views
0

以下成员函数在主事件循环中运行。Qt:立即启动线程,不会延迟主事件循环

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

+0

你的意思是,结果是在准备好时'...更新...'仍然忙? – 2015-02-24 14:59:38

+0

不!但是计算已经可以并行开始,不需要完成。更新上面,使其更明显 – 2015-02-24 15:04:57

+0

如果doCalculations没有触发,那么我的猜测是它*不是在另一个线程中。你有没有正确地调用moveToThread呢? – 2015-02-24 15:08:59

回答

1

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

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

顺便说一句,为了有平行执行,你将不得不使用threads。 一个代码片断应该是:

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

正如我写的,CInterpolator是一个QObject驻留在另一个线程http://qt-project.org/doc/qt-4.8/qobject.html#moveToThread,所以它的亲和力是新线程的亲和力。这并不是说应用程序没有响应,尤其不是因为我已经从主事件循环中计算出来了。只有直到计算开始的延迟才是不理想的。 – 2015-02-24 15:12:49

+0

我已经用线程使用的代码片段更新了我的答案。更好地将更新封装在一个函数中,该函数将由名为**的线程首先执行** – otorrillas 2015-02-24 15:16:48

+0

从编辑开始:因此,您的建议是使用std :: thread而不是Qt的线程机制。这是这个想法吗? – 2015-02-24 15:19:21