gpt4 book ai didi

Qt Main-Gui 和其他线程+事件循环

转载 作者:行者123 更新时间:2023-12-04 12:48:14 26 4
gpt4 key购买 nike

我试图了解 Qt 的整个内部过程以及当我使用不同的线程时它是如何工作的。

据我了解(谷歌搜索和探索 Qt 源代码),如下所示:

  • 每个线程都有一个本地“待处理事件列表”和一个与该列表交互的本地事件循环(如果我调用 exec)。
  • QCoreApplication::postEvent(obj, e)附加对 (obj, e)obj 的“待定事件列表”中的线程。
  • 每个线程都有一个本地“事件调度器”(QAbstractEventDispatcher 特化),其目的是读取系统事件。所以,它存在一个 QEventDispatchWin , 一个 QEventDispatchUnix , 一个 QEventDispatchSymbian等等,针对不同的平台。对于 gui事件,Qt 也有 QEventDispatchX11 (继承自 QEventDispatchUnix ),S60 (来自 Symbian )等

  • 考虑到这一切, exec调用工作如下:
    Thread's `exec`:
    ├ create a QEventLoop object.
    └ call QEventLoop.exec()
    └ call repeatedly eventDispatcher's processEvents with WaitForMoreEvents flag.
    ├ call to QCoreApplication::sendPostedEvents
    ├ while (!pending system events)
    │ ├ read system event
    │ ├ create an appropiate QEvent e and detect its target QObject o.
    │ └ call to QCoreApplication::sendSpontaneousEvent(o, e)
    └ call to QCoreApplication::sendPostedEvents
    (for new generated user events in the previous step).

    如果 quitexit被调用,它结束当前的 processEvents调用和 exec返回传递给 exit 的值.

    需要考虑的几点:
  • 系统事件从不推送/发布:当它们从系统生成并转换为 QEvents 时,它们会直接发送到其目标对象。
  • 目标对象成员函数 ( o.event() ) 在与 processEvent 相同的线程中被调用。发生。

  • 现在,怀疑:
  • 由于postEvent是一个静态和线程安全的函数,QCoreApplication 在这个事件处理系统中扮演什么角色? QApplication?为什么它们必须尽快创建?
  • 如果每个线程都有自己的“事件调度程序”,为什么 QApplication/QCoreApplication 必须获取系统事件?

  • 欢迎对我的假设进行任何更正。

    最佳答案

    回答您的第二个问题,“如果每个线程都有自己的“事件调度程序”,为什么 QApplication/QCoreApplication 必须强制获取系统事件?”

    4.8 文档指出:

    "Note that QCoreApplication::exec() must always be called from the main thread (the thread that executes main()), not from a QThread. In GUI applications, the main thread is also called the GUI thread because it's the only thread that is allowed to perform GUI-related operations."



    但是关于一般的 QThreads - 您会发现提供的链接将 QThreads 描述为 QObjects,它是线程的包装器。因此,QThreads 与任何其他 QObjects 一样,需要 QCoreApplication 与之交互以协调通知/事件,例如当线程完成时。

    http://qt-project.org/forums/viewthread/14806

    在 Maya 的文章中,她提供了一个示例,其中任务被分配给 QThread,而不是在 [i.e.使用信号/插槽,不要重载 run() 方法]。这样,你就清楚的看到 QCoreApplication 提供的主事件循环仍然起到了至关重要的作用。

    正如您可能已经知道的那样,在这个网站上已经围绕 QThreads 主题展开了大量讨论——Qt4 的文档非常完善......不能对 Qt5 说同样的话 =(

    关于Qt Main-Gui 和其他线程+事件循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16812602/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com