Qt的默认线程 [英] Qt's default threads

查看:100
本文介绍了Qt的默认线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我用最少的代码启动一个新的Qt应用程序并运行它时,我看到有许多正在运行的线程,其数量最少为2,最多可以为5.通常为2 ,直到我拖动窗口,这时我最多看到4个线程在运行.

When I start a new Qt application with a minimal amount of code and run it, I see that there are a number of threads running, which at a minimum is 2 and can be as many as 5. It usually settles at 2, until I drag the window around, at which time I see up to 4 threads running.

这是我正在使用的所有代码:-

This is all the code I'm using: -

#include <QApplication>
#include <QWidget>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QWidget mainWindow;
    mainWindow.show();

    return a.exec();
}

有人可以解释为什么会有不同的线程以及它们可能是做什么用的吗?最初我只期望一个,但是如果使用一秒钟来处理消息,也不会感到惊讶.但是,其他线程又有什么原因呢?

Can someone explain why there are different threads and what they're likely to be for? Originally I expected just one, but wouldn't be surprised if a second was used for handling messages. However, what could account for the other threads?

推荐答案

我现在看到您是出于好奇而不是实际问题.让我们做些研究.

I see now that you're asking out of curiosity in opposite to practical problems. Let's do some research.

我尝试使用Windows上的MSVC工具包在Qt 5.1上运行您的程序.我将调试器配置为在线程创建时中断.我看到产生了另外4个线程.其中3个是由Qt调用RegisterDragDrop本机Windows函数引起的.当我跳过QWindowsWindow::registerDropSite执行时,不会创建这3个线程.即使在RegisterDragDrop文档中也没有关于线程的解释,更不用说Qt文档了.显然,当使用不同的OS或Qt版本时,此事实可能会有所不同(例如,您可以在不支持拖放的情况下构建Qt).找出为什么为您创建线程的唯一方法是进行实验.我认为OS X也为您带来一些惊喜.

I've tried to run your program on Qt 5.1 with MSVC toolkit on Windows. I configured the debugger to break on thread creation. I saw that 4 additional threads have been spawned. 3 of them were caused by Qt calling RegisterDragDrop native Windows function. When I skip QWindowsWindow::registerDropSite execution, these 3 threads are not created. There is no explanation about the threads even in the RegisterDragDrop documentation, not to say about Qt documentation. Obviously this fact can vary when using different OSs or Qt versions (for example you can build Qt without drag-n-drop support). The only way you can find out why the threads were created for you is an experiment. I think OS X also has some surprises for you.

第4个线程对我来说是个谜:调试器无法检测到何时启动.也许此线程是由调试器导致的.

The 4th thread is a mystery to me: debugger cannot detect when it is started. Maybe this thread is caused by debugger somehow.

正如我所料,@tebe说Qt产生了用于QTimer处理的其他线程是错误的(我不了解所有情况,但是在我看来,这肯定是不正确的). QTimer使用当前线程的事件循环.

As I expected, @tebe was wrong saying that Qt spawns additional threads for QTimer processing (I don't know about all cases, but in my case this is surely incorrect). QTimer uses the event loop of current thread.

这篇关于Qt的默认线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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