Qthread,为qthread添加功能

Qthread,adding function to qthread

本文关键字:添加 功能 qthread Qthread      更新时间:2023-10-16

我有这样的类

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,我已经看过教程,它们都只是为了类而不是为了一个函数?

如果需要在单独的线程上运行函数,可以使用如下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.