简体   繁体   English

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

[英]2 independent std threads in Qt Gui Application

I want to make my application multithreaded. 我想使我的应用程序成为多线程。 When I added 2 separate independent threads I have got runtime error message. 当我添加2个独立的独立线程时,出现运行时错误消息。 I can't find the solution. 我找不到解决方案。 Perhaps someone may help. 也许有人可以帮忙。

Here is link to runtime error image https://postimg.org/image/aasqn2y7b/ 这是运行时错误图像的链接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 main.cpp

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

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

    MainWindow w;
    w.show();

    return a.exec();
 }

Your start thread two is broken: 您的第二个启动线程已损坏:

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

After starting thread one, m_thread_one gets another thread assigned. 在启动线程一之后,m_thread_one将分配另一个线程。 However, the thread one is not joined, hence the termination. 但是,线程一未连接,因此终止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM