使用QtConcurrent在QT中进行多线程 [英] Multithreading in QT using QtConcurrent

查看:938
本文介绍了使用QtConcurrent在QT中进行多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Qt中开发一个应用程序,该应用程序有时会处理大量视频. 它工作正常,但是在处理阶段它仅占用40-60%的cpu使用率,因此我尝试将其设置为多线程.

Im developing an application in Qt which, at some point, process a bunch of videos. It works fine but it had only a 40-60% of the cpu usage during the process phase so i tried to make it multithreaded.

我使用QtConcurrent导致他的高水平"而不是更传统的线程管理,我的代码很简单:

I used QtConcurrent cause his 'high leveness' instead a more traditional thread management, my code is simply:

for(int i = 0; i < totalVideos; i++)
{
    QFuture<ResultClass *> futureToken = QtConcurrent::run(this, process, listOfVideos.takeFirst());
    QFutureWatcher<ResultClass *>* fw = new QFutureWatcher<ResultClass *>();
    connect(fw, SIGNAL(finished()), this, SLOT(manageResult));
    fw->setFuture(futureToken);
}

aaa并能正常工作,CPU使用率达到100%,速度提高了25-30%.但是它产生了大约65个新线程(无论它处理25或250个视频),而且大多数线程在处理阶段之后都不会消失.

aaaand it works, 100% cpu usage and its around 25-30% faster. But it spawns around 65 new threads (regardless it process 25 or 250 videos) and most of those threads doesn't disappear after the process phase.

我的问题是:这种方法正确吗?太生了吗?我应该手动"控制线程的创建吗? QtConcurrent模块可以照顾所有人,所以我不应该照顾线程管理吗? 85个线程过多吗?在流程阶段之后,我应该尝试杀死其中的一些人吗?

My question is: Is this approach right? Is it too raw? Should i control 'manually' the thread creation? Does the QtConcurrent module takes care of all so i should not care of the thread management? Are 85 threads too much? Should i try to kill some of those after the process phase??

只需观察活动"监视器即可完成所有观察.

Every observation has been done just looking at the Activity monitor.

谢谢.

推荐答案

如果您阅读拥有更多线程来处理内核有些多余.如果您有一个内核和2个线程在运行,则处理器会花费时间在处理2个线程之间进行切换,但是会为用户提供同步处理的外观.

Having more threads that processing cores is somewhat redundant. If you have one core and 2 threads running, the processor spends time switching between the processing the 2 threads, but gives the user the appearance of simultaneous processing.

使用相同数量的内核和线程,可以在内核之间分配线程.

With the same number of cores and threads, the threads can be split between the cores.

一旦内核数多于线程数,您将回到原始的方法,即在需要处理的线程之间来回跳动.

Once you have more cores than threads, you're back to the original method of cores jumping up and back between the threads that it is required to process.

使用QThread实际上非常容易,因为QThread不是直接属于线程,而是线程控制器.您可以阅读有关如何

Using QThread is actually very easy to do as QThread is not directly a thread, but a thread controller. You can read about how to 'really truly use QThreads' here.

如前所述,您将创建继承给QObject的对象,然后将其移至QThread.很少提及的是,如果需要,可以将多个对象移至新的QThread.

As it describes, you create objects inherited to QObject and move that to a QThread. What is rarely mentioned is that you can move multiple objects to the new QThread, if required.

这篇关于使用QtConcurrent在QT中进行多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆