Ich möchte meine Anwendung Multithread machen. Wenn ich 2 separate unabhängige Threads hinzugefügt habe, habe ich eine Laufzeitfehlermeldung erhalten. Ich kann die Lösung nicht finden. Vielleicht kann jemand helfen.2 unabhängige Std-Threads in Qt Gui Anwendung
Hier Link Fehlerbild 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();
}
Ihr Link zur Fehlermeldung ist beschädigt. Bitte posten Sie die Nachricht als Text. –
Ich denke, das ist nicht die Auflösung, aber Sie teilen std :: atomic m_stopper in beiden Threads ohne Mutex. Versuchen Sie, das Konsolenprotokoll in Ihren Post zu setzen –
uelordi
Der Link funktioniert. Ich habe es vor einer Minute überprüft. Aber nur für den Fall, dass ich Ihnen den Text zur Verfügung stellen: Microsoft Visual C++ Laufzeitbibliothek Laufzeitfehler! –