简体   繁体   中英

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. I can't find the solution. Perhaps someone may help.

Here is link to runtime error image 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();
 }

Your start thread two is broken:

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

After starting thread one, m_thread_one gets another thread assigned. However, the thread one is not joined, hence the termination.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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