2015-02-24 127 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