c++ - QtConcurrent 与多线程的 QThread 的多线程性能

标签 c++ multithreading qt qthread qtconcurrent

假设您的应用程序需要在多个线程中运行一个函数,这些线程的数量大于 CPU 内核/线程的数量。一种方法是使用 QtConcurrent 并设置最大线程数:

MyClass *obj = new MyClass;

QThreadPool::globalInstance()->setMaxThreadCount(30);

for(int i=0;i<30;i++)
    QtConcurrent::run(obj, &MyClass::someFunction);

另一种方法是拥有多个对象并使用 moveToThread 将它们移动到不同的线程:

for(int i=0;i<30;i++)
{
        MyClass *obj = new MyClass;
        QThread *th = new QThread();
        obj->moveToThread(th);
        connect(th, SIGNAL(started()), obj, SLOT(someFunction()) );
        connect(obj, SIGNAL(workFinished()), th, SLOT(quit()) );
        connect(th, SIGNAL(finished()), obj, SLOT(deleteLater()) );
        connect(th, SIGNAL(finished()), th, SLOT(deleteLater()) );

        th->start();
}

由于线程数多于CPU核数,因此运行时需要在不同核之间切换线程。

问题是这两种方法是否有不同的表现?即 QThread 的切换与使用 QtConcurrent::run 运行的切换不同吗?

最佳答案

我同意第一个答案,但我想补充一点。

QThread是仅运行特定于操作系统的功能的低级类。什么是QtConcurrent ?答案在Qt源代码。

第一层:run

QFuture<T> run(T (*functionPointer)())  
{
        return (new StoredFunctorCall0<T, T (*)()>(functionPointer))->start();
}

Second :

struct StoredFunctorCall0: public RunFunctionTask<T>    { ...

Third :

template <typename T>
class RunFunctionTaskBase : public QFutureInterface<T> , public QRunnable
{ ...

现在关于 QRunnable .当我们开始 QRunnableQThreadPool我们这样做:

start()调用 tryStart()调用 startThread()使用 QThreadPoolThread 操作(它是 QThread subclass )最后调用 start()QThread .

当然,这条链条并不完整,很长的路,不是吗?所以据我所知,当我们使用抽象时,我们有抽象惩罚( QtConcurrentQThread 有更大的惩罚),但最终结果是相同的,它是 QThread .

关于c++ - QtConcurrent 与多线程的 QThread 的多线程性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30680358/

相关文章:

c++ - 如何返回指向链表中最大值的指针?

c - 使用 pthread_join 的 pthread 同步问题

python - 如何在与主程序不同的线程中编写套接字服务器(使用gevent)?

c - C 中的线程同步 : why do they overlap

c++ - Qt 停止应用程序一段时间

c++ - 将 OpenGL 中的特定相机 View 保存为图像

python - 使用多个函数参数调用 PyObject_CallObject

c++ - 链接错误 : QtCore. framework/Versions/4/QtCore for architecture x86_64

c++ - 正则表达式每两个字符拆分字符串

c++ - QObject::connect 与连接方法之间的区别