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
应该是不言自明的;它将在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()。在启动程序的清理/退出阶段之前,从主线程对每个线程对象调用它。它将等待线程退出后再返回。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- C++,系统无法执行指定的程序
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到
- 重载操作程序时出错>>用于类中的字符串 memebr
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 试图在visual studio上用C++创建一个桌面应用程序
- 模板元程序查找相似的连续类型名称
- FFmpeg:制作一个应用程序比直接使用ffmepg更好吗
- 如何通过cpp程序运行shell脚本
- QT QThread::is在Pi上运行冻结程序
- Qthread中的运行功能 - 应用程序将悬挂
- C++Qt5-程序在QThread之前完成
- 当应用程序在没有适当的 wait() 调用的情况下关闭时,QThread 会发生什么
- QThread::msleep() 冻结程序
- 可能是QThread内部的QTLineEdit的范围导致程序崩溃
- 无法关闭QThread-应用程序崩溃
- QT Creator:程序在调试模式下崩溃,但在发布模式下工作,在基于QThread的程序的调试模式下有断点
- 在嵌入式PyQt应用程序中使用QThread