gpt4 book ai didi

c++ - QThread finish() 连接到 QObject 的删除

转载 作者:行者123 更新时间:2023-12-02 12:13:09 24 4
gpt4 key购买 nike

在提出这个问题之前,我想了很多,也读了很多文章。这些文章都没有给我正确的答案。

http://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/

 QThread* thread = new QThread;
Worker* worker = new Worker();
worker->moveToThread(thread);
connect(worker, SIGNAL(error(QString)), this, SLOT(errorString(QString)));
connect(thread, SIGNAL(started()), worker, SLOT(process()));
connect(worker, SIGNAL(finished()), thread, SLOT(quit()));
connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater()));
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();

Worker 对象具有新线程的亲和性。

  1. Worker 完成信号将在线程上调用 quit()。这将结束线程的事件循环并启动线程完成信号。

  2. Worker finished 信号已连接到 Worker deleteLater()。根据 deleteLater() 文档

Schedules this object for deletion.The object will be deleted when control returns to the event loop.If the event loop is not runningwhen this function is called (e.g. deleteLater() is called on anobject before QCoreApplication::exec()), the object will be deletedonce the event loop is started.

Note that entering and leaving a newevent loop (e.g., by opening a modal dialog) will not perform thedeferred deletion; for the object to be deleted, the control mustreturn to the event loop from which deleteLater() was called.

Note: Itis safe to call this function more than once; when the first deferreddeletion event is delivered, any pending events for the object areremoved from the event queue.**

因此,当没有事件循环时,由于线程已经退出并且它已经引发了完成信号,因此我们将不再再次启动同一线程。在这种情况下,deleteLater() 将永远不会被处理,因为事件循环不存在,并且工作对象根本不会被删除。这不会造成内存泄漏吗?

 connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater()));
connect(worker, SIGNAL(finished()), thread, SLOT(quit()));

如果我们认为交换两条线可以解决问题,那么我还有另一个问题。 QT 明确指出,发出信号时调用槽的顺序是不确定的

上面提到的文章链接里有一堆评论。就连作者也无法完全回答这个问题

最佳答案

QThread 将执行 QCoreApplication::sendPostedEvents发送完成信号后事件类型为 QEvent::DeferredDelete

换句话说,QThread将收集所有待处理的deleteLaters,并在run返回后执行它们

来源:https://qt.gitorious.org/qt/qtbase/source/c657bb7b51115d6e1719166fb502bb0ca1dcf4e8:src/corelib/thread/qthread_win.cpp#L363-462

关于c++ - QThread finish() 连接到 QObject 的删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12114604/

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