Qt Gui应用程序中有2个独立的std线程

时间:2016-06-30 11:57:12

标签: c++ multithreading qt

我想让我的应用程序多线程化。当我添加2个独立的独立线程时,我收到了运行时错误消息。我无法找到解决方案。也许有人可以提供帮助。

以下是运行时错误图像https://postimg.org/image/aasqn2y7b/

的链接

threads.h

#include <thread>
#include <atomic>
#include <chrono>
#include <iostream>

class Threads
{
public:
    Threads() : m_threadOne(), m_threadTwo(), m_stopper(false) { }

    ~Threads() {
        m_stopper.exchange(true);

        if (m_threadOne.joinable()) m_threadOne.join();
        if (m_threadTwo.joinable()) m_threadTwo.join();
    }

    void startThreadOne() {
        m_threadOne = std::thread([this]() {
            while (true) {
                if (m_stopper.load()) break;

                std::cout << "Thread 1" << std::endl;
                std::this_thread::sleep_for(std::chrono::seconds(1));
            }
        });
    }

    void startThreadTwo() {
        m_threadOne = std::thread([this]() {
            while (true) {
                if (m_stopper.load()) break;

                std::cout << "Thread 2" << std::endl;
                std::this_thread::sleep_for(std::chrono::seconds(1));
            }
        });
    }

private:
    std::thread m_threadOne;
    std::thread m_threadTwo;
    std::atomic<bool> m_stopper;
};

mainwindow.h

#include "threads.h"
#include <QMainWindow>
#include "ui_mainwindow.h"

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0) : QMainWindow(parent), ui(new Ui::MainWindow), m_threads() {
        ui->setupUi(this);

        m_threads.startThreadOne();
        m_threads.startThreadTwo();
    }

    ~MainWindow() { delete ui; }

private:
    Ui::MainWindow *ui;
    Threads m_threads;
};

的main.cpp

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    MainWindow w;
    w.show();

    return a.exec();
 }

1 个答案:

答案 0 :(得分:5)

您的启动主题2已损坏:

m_threadOne = std::thread([this]() { ... });

启动第一个线程后,m_thread_one会分配另一个线程。但是,线程1没有连接,因此终止。