【问题标题】:How to use std::thread with Qt's main event loop?如何在 Qt 的主事件循环中使用 std::thread?
【发布时间】:2015-09-04 13:47:18
【问题描述】:

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

terminate called without an active exception
Aborted (core dumped)

应该有什么问题?当我在 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;
}

【问题讨论】:

  • 我有一个问题。我想在我的项目中使用线程(不是 QThread)。我添加了 refrence #include ,但我的 Qt 类不知道 std::thread。我该如何解决?

标签: c++ multithreading qt c++11


【解决方案1】:

主线程

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;
}

包括问题

永远不要通过&lt;QtModule/Class&gt; 包含。这隐藏了项目文件中的配置错误。您应该一个接一个地包含各个类,一次性包含整个模块的声明。

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

#include <QtGui> // Qt 4 only
#include <QtWidgets> // Qt 5 only

#include <QApplication> // Qt 4/5
#include <Q....> // etc.

【讨论】:

    【解决方案2】:

    你的程序崩溃的真正原因是如果线程既没有加入也没有分离,std::thread 在它的析构函数中抛出异常。

    为避免崩溃,您需要加入两个线程。

    【讨论】:

      【解决方案3】:

      您的 main 函数在创建线程后返回,导致您的程序退出并终止所有正在运行的线程。在两个线程上调用 join 以便主函数在线程自行终止之前不会返回。

      【讨论】:

      • 实际原因没有正确概述。看我的回答。
      猜你喜欢
      • 2019-12-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-10
      • 1970-01-01
      • 2014-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多