为什么当我第二次尝试启动同一个线程时,应用程序会崩溃
Why does the application crash when I try to start the same thread a second time?
main.cpp:
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
mainwindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
cThread = new QThread(this);
cObject = new MyObject();
cObject->moveToThread(cThread);
QObject::connect(ui->pushButton_3, SIGNAL(clicked()),
this, SLOT(close())
);
QObject::connect(cThread, SIGNAL(started()),
cObject, SLOT(doWork())
);
QObject::connect(ui->pushButton_4, SIGNAL(clicked()),
this, SLOT(runThreadSlot())
);
QObject::connect(cThread, SIGNAL(finished()),
cThread, SLOT(deleteLater())
);
QObject::connect(cThread, SIGNAL(finished()),
cObject, SLOT(deleteLater())
);
QObject::connect(cObject, SIGNAL(setStatusBarSignal(QString)),
this, SLOT(setStatusBarSlot(QString))
);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::runThreadSlot()
{
cThread->start();
}
void MainWindow::setStatusBarSlot(QString text)
{
ui->statusBar->showMessage(text);
}
myobject.cpp:
#include "myobject.h"
MyObject::MyObject(QObject *parent) :
QObject(parent)
{
}
void MyObject::doWork()
{
emit setStatusBarSignal(QString::number((qint32) QThread::currentThreadId()));
QThread::currentThread()->quit();
return;
}
主窗口.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "myobject.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void runThreadSlot();
void setStatusBarSlot(QString);
private:
Ui::MainWindow *ui;
QThread* cThread;
MyObject* cObject;
};
#endif // MAINWINDOW_H
myobject.h:
#ifndef MYOBJECT_H
#define MYOBJECT_H
#include <QtCore>
class MyObject : public QObject
{
Q_OBJECT
public:
explicit MyObject(QObject *parent = 0);
signals:
void setStatusBarSignal(QString);
public slots:
void doWork();
};
#endif // MYOBJECT_H
所以模式是:
pushButton_4单击((--->runThreadSlot((--->cThread start((
线程立即使用QThread::currentThread()->quit();
自行终止,但当我再次单击pushButton_4时,应用程序崩溃。
这很可能是您的问题。
QObject::connect(cThread, SIGNAL(finished()),
cThread, SLOT(deleteLater())
);
QObject::connect(cThread, SIGNAL(finished()),
cObject, SLOT(deleteLater())
);
想想发射完信号后会发生什么。
相关文章:
- Qt C++静态thread_local QNetworkAccessManager是线程应用程序的好选择吗
- 通过安装信号处理程序关闭多线程应用程序
- 将数组作为多线程应用程序中函数的返回传递
- 修改多线程应用程序中的对象
- C++多线程应用程序将永远挂起
- 具有多线程应用程序的 Nanomsg 无阻塞双向套接字
- 在接收 SIGINT 操作时适当地关闭多线程 c++ 应用程序
- 如何在多线程应用程序中获得花费的时间
- Linux VM(重型多线程应用程序)的性能改进
- 在C 多线程应用程序中,设置了并发线程的最大数量
- C++多线程应用程序崩溃
- 多线程应用程序中的零MQ处理中断
- 使用C 的多线程应用程序中测量全局时间(壁挂)的最快方法
- 如何在多线程应用程序中使用 pybind11
- 多线程应用程序中的独立日志记录
- 如何在不冻结线程/应用程序的情况下减慢方法执行速度
- 设计一个扩展良好的多线程应用程序
- 在 Linux 上为 Windows 编译多线程应用程序 [ C++ ]
- 如何为多线程应用程序创建全局对象
- 管理多线程应用程序中的共享变量