[英]How to use std::thread with Qt's main event loop?
In this code Qt part (fun1()) always crashes. 在此代码Qt部分(fun1())始终崩溃。 It writes:
它写道:
terminate called without an active exception
Aborted (core dumped)
What should be wrong? 怎么了 When I call Qt stuff in main, and I do not use threads it works well, but I need to call another function and use threads (fun2() is just for ilustration) My code is here:
当我在main中调用Qt东西时,我不使用线程,但是它工作良好,但是我需要调用另一个函数并使用线程(fun2()仅用于说明)我的代码在这里:
#include "../common/main_window.hpp"
#include <QtGui/QApplication>
#include <QtGui>
#include <thread>
#include <iostream>
int argc_;
char **argv_;
void fun1()
{
QApplication a(argc_,argv_);
MainWindow w;
w.show();
a.exec();
}
void fun2()
{
std::cout << "Print something" << std::endl;
}
int main(int argc, char **argv)
{
//argc_ = malloc((1)*sizeof(char*));
argc_= argc;
argv_= argv;
std::thread first(fun1);
std::thread second(fun2);
return 0;
}
Qt does not support running the GUI event loop in any thread but the main thread. Qt不支持在除主线程之外的任何线程中运行GUI事件循环。 What you do happens to work on Windows, and might work on some Unixes, but it will never work on OS X or iOS, for example.
您所做的事情恰好在Windows上可以运行,并且可能在某些Unix上可以运行,但是例如在OS X或iOS上永远无法运行。 So, in production code, there's no place for you running the threads like you do.
因此,在生产代码中,没有地方像您一样运行线程。
fun1()
should be called from main
, and you must wait for the other thread's functor to finish before you destruct the thread. 应该从
main
调用fun1()
,并且在破坏线程之前,必须等待另一个线程的函子完成。
int fun1(int & argc, char ** argv)
{
// QApplication might modify argc, and this should be fed back to
// the caller.
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
int main(int argc, char **argv)
{
std::thread worker(fun2);
int rc = fun1(argc, argv);
worker.join();
return rc;
}
Never include through <QtModule/Class>
. 切勿通过
<QtModule/Class>
包括在内。 This hides the configuration mistakes in your project file. 这会将配置错误隐藏在您的项目文件中。 You should either include individual classess one-by-one, or include the entire module's declarations in one go.
您应该一个一个地包含单个类, 或者一次包含整个模块的声明。
Thus, your test case should have either of the two following include styles: 因此,您的测试用例应具有以下两个包含样式之一:
#include <QtGui> // Qt 4 only
#include <QtWidgets> // Qt 5 only
or 要么
#include <QApplication> // Qt 4/5
#include <Q....> // etc.
The actual reason why your program crashes is that std::thread throws exception in it's destructor if thread was neither joined nor detached. 程序崩溃的真正原因是,如果既未加入线程也未分离线程,则std :: thread在其析构函数中引发异常。
To avoid the crash, you need to join your both threads. 为了避免崩溃,您需要同时加入两个线程。
Your main function returns after creating the threads, causing your program to exit and terminating all running threads. 主函数在创建线程后返回,从而导致程序退出并终止所有正在运行的线程。 Call
join
on both threads so the main function doesn't return until the threads terminate by themselves. 在两个线程上都调用
join
,因此直到线程自行终止后,main函数才返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.