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

C++ Qt5 - Program finishes before QThread

我们来看看下面的代码:

class CommandRetriever
{
    public:
        CommandRetriever();
        ~CommandRetriever();
    
        void addCommand( QString, Command* );
        void executeCommands();

    private:
        QMap<QString, Command*> m_commands;
};

addCommand 应该是不言自明的;它将在 m_commands 中添加一个新条目。但是,让我们看一下 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,它有 public 插槽 doAsync() 来完成主线程之外的工作。所有这些都是根据 Qt 官方示例以及我从各种博客中收集到的内容。

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


问题

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

谢谢!


2015 年 4 月 20 日补遗

虽然 Jeremy 在这个问题中接受的答案是正确的,但对于基于控制台的应用程序来说意义不大,因为在这些应用程序中通常不需要事件循环。

因此,我问了一个新问题,并为那些正在寻找没有 Qt 事件循环废话的线程的人找到了答案:

您要找的方法是QThread::wait()。在开始程序的 cleanup/exit 阶段之前,从主线程在每个线程对象上调用它。它会等到线程退出后再返回。