如何在Qt的主事件循环中使用std :: thread?

0 c++ qt multithreading c++11

在这段代码中,Qt部分(fun1())总是崩溃.它写道:

terminate called without an active exception
Aborted (core dumped)
Run Code Online (Sandbox Code Playgroud)

应该怎么做?当我在main中调用Qt的东西时,我不使用线程它运行良好,但我需要调用另一个函数并使用线程(fun2()仅用于ilustration)我的代码在这里:

#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;
}
Run Code Online (Sandbox Code Playgroud)

Rei*_*ica 8

主线程

Qt不支持在主线程的任何线程中运行GUI事件循环.您所做的事情恰好在Windows上运行,并且可能适用于某些Unix,但它永远不会在OS X或iOS上运行.因此,在生产代码中,没有像你那样运行线程的地方.

fun1()应该从中调用main,并且在破坏线程之前必须等待另一个线程的仿函数完成.

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;
}
Run Code Online (Sandbox Code Playgroud)

包括问题

永远不要包括<QtModule/Class>.这会隐藏项目文件中的配置错误.您应该逐个包含单个classess,或者一次性包含整个模块的声明.

因此,您的测试用例应具有以下两种包含样式之一:

#include <QtGui> // Qt 4 only
#include <QtWidgets> // Qt 5 only
Run Code Online (Sandbox Code Playgroud)

要么

#include <QApplication> // Qt 4/5
#include <Q....> // etc.
Run Code Online (Sandbox Code Playgroud)