2016-06-30 50 views
1

我想讓我的應用程序多線程。當我添加2個獨立的獨立線程時,我得到了運行時錯誤消息。我找不到解決方案。也許有人可能會幫助。Qt中的2個獨立的std線程應用程序

這裏是鏈接運行時錯誤圖像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(); 
} 
+0

您的錯誤消息鏈接已損壞。請以文字形式發佈信息。 –

+0

我想這不是靈魂,但你在兩個線程中共享std :: atomic m_stopper沒有互斥。嘗試把控制檯登錄到你的文章 – uelordi

+0

鏈接工作。我剛纔檢查了一下。 但是,以防萬一我會爲您提供文本: Microsoft Visual C++運行時庫 運行時錯誤! –

回答

5

你開始線程2破壞:

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

在啓動線程之後,m_thread_one會獲取另一個分配的線程。但是,線程不加入,因此終止。

+1

複製粘貼反擊:-) – hyde

+0

謝謝,現在我明白了。我的錯誤,我不得不在這裏使用m_threadTwo –