2013-12-22 36 views
4

我有這樣的的QThread,增加功能的QThread

class Class1 : public QObject 
{ 
    Q_OBJECT 
    void a(); 
    void b(); 
    ........... 

void Class1:a() 
{ 
    for(int i=0;i<10;i++) 
     b();//I want here to make parallel 

      //and wait here all threads are done 


} 

我怎麼能在這裏qhthread使用類,我已經看了教程他們都只是不是一個函數類的?

回答

4

如果您需要在一個單獨的線程運行的函數,你可以使用QtConcurrent這樣的:

QtConcurrent::run(this, &Class1::b); 

編輯:您可以使用QFutureSynchronizer等待所有線程,不要忘記分配所有線程使用QThreadPool::globalInstance()->setMaxThreadCount()

編輯2:您可以使用synchronizer.futures()來獲取所有線程的返回值。

例子:

QThreadPool::globalInstance()->setMaxThreadCount(10); 
QFutureSynchronizer<int> synchronizer; 
for(int i = 1; i <= 10; i++) 
    synchronizer.addFuture(QtConcurrent::run(this, &Class1::b)); 
synchronizer.waitForFinished(); 
foreach(QFuture<int> thread, synchronizer.futures()) 
    qDebug() << thread.result(); //Get the return value of each thread. 
+0

謝謝你,以及如何功能(一)可以等到所有胎面完成。 –

+0

@BMacit,看我上面的編輯。 –

+0

謝謝@ user2014561我問這麼多,但最後一個問題是,如果b返回一個值,我們如何才能得到它(例如:int b()) –