C++Qt5-程序在QThread之前完成

C++ Qt5 - Program finishes before QThread

本文关键字:QThread 程序 C++Qt5-      更新时间:2023-10-16

让我们看看下面的代码:

class CommandRetriever
{
public:
CommandRetriever();
~CommandRetriever();

void addCommand( QString, Command* );
void executeCommands();
private:
QMap<QString, Command*> m_commands;
};

addCommand应该是不言自明的;它将在CCD_ 2中添加一个新的条目。然而,让我们来看看executeCommands的实现。。。

void CommandRetriever::executeCommands()
{
for( auto iter : m_commands.keys() )
{
Command *cmd = m_commands.value( iter ); 

// Command, password //
RemoteConnection *rcon = new RemoteConnection( cmd, "" );
QThread *thread = new QThread();
rcon->moveToThread( thread );
QObject::connect( thread, SIGNAL( started() ), rcon, SLOT( doAsync() ) );
QObject::connect( rcon, SIGNAL( finished() ), thread, SLOT( quit() ) );
QObject::connect( rcon, SIGNAL( finished() ), rcon, SLOT( deleteLater() ) );
QObject::connect( thread, SIGNAL( finished() ), thread, SLOT( deleteLater() ) );
thread->start();
}
}

我的rcon对象是一个QObject,它有一个公共槽doAsync()来完成主线程之外的工作。所有这些都是每个Qt的官方例子,也是我从各种博客中收集到的。

这是一个完全基于控制台的程序,所以我没有Windows、小工具或事件循环可供使用。


问题

发生的情况是,我的程序将在完成任何异步工作(例如,连接到远程主机、写入数据等)之前退出。有时,如果幸运的话,我的线程会以足够快的速度输出一些东西,所以我知道线程正在正常工作。我的问题是:如何保持主程序运行,直到线程完成工作QThread中有官方的方法吗?因为我在文件里什么都没看到。

谢谢!


附录2015年4月20日

尽管Jeremy在这个问题中给出的公认答案是正确的,但对于基于控制台的应用程序来说,这没有什么意义,因为在控制台中通常不需要事件循环。

因此,我提出了一个新问题,并为那些寻求使用没有Qt事件循环的线程的人找到了一个答案:

QThread从未因QCoreApplication事件循环而退出

您要查找的方法是QThread::wait()。在启动程序的清理/退出阶段之前,从主线程对每个线程对象调用它。它将等待线程退出后再返回。