C++ Qthread,向Qthread添加函数
我有一节这样的课C++ Qthread,向Qthread添加函数,c++,multithreading,qt,qthread,C++,Multithreading,Qt,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 } 类1:公共Q
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
}
类1:公共QObject
{
Q_对象
使a()无效;
无效b();
...........
空类1:a()
{
对于(int i=0;i如果您需要在单独的线程上运行函数,您可以这样使用:
QtConcurrent::run(this, &Class1::b);
编辑:您可以使用等待所有线程,不要忘记使用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.
QThreadPool::globalInstance()->setMaxThreadCount(10);
未来同步器;
对于(int i=1;我感谢您,也感谢函数(a)如何等待所有步骤完成。谢谢@user2014561我问了这么多,但最后一个问题是,如果b返回一个值,我们如何获得它(例如:int b())setMaxThreadCount函数真的需要吗?如果很难估计所需的线程数怎么办?@ejectamenta:这取决于,如果线程池中已经有了要并行使用的线程数,那么就不需要重新分配它们。这样做只是为了确定。如果不确定要分配多少个池线程,那么我使用,您可以在如下方式启动每个线程之前再分配一个池线程:int-maxthread=QThreadPool::globalInstance()->maxThreadCount()+1;QThreadPool::globalInstance()->setMaxThreadCount(maxthread);