线程的安全退出问题:
由于遇到了
//QThread: Destroyed while thread is still running //已放弃
所以认真的研究了一下这个问题,下面给出一个具体实验环境(qt5),即可说明问题.
简单期间,直接上代码, 分三部分,header文件,cpp文件,pro文件, 重点在主窗口的析构,有注释说明如何停止线程的运行.
header 文件
cat *.h
#ifndef _CLOCK_THREAD_H
#define _CLOCK_THREAD_H
#include <QThread>
class ClockThread: public QThread
{
Q_OBJECT
public:
ClockThread(QObject *parent = nullptr);
~ClockThread() {}
void run() ;
void set_thread_runing(bool thread_runing);
private:
bool m_thread_runing;
signals:
void sigReady();
};
#endif
#ifndef _MAINW_H
#define _MAINW_H
#include <QMainWindow>
class ClockThread;
class MainWindow :public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent=0);
~MainWindow();
private slots:
void slot_updateClock();
private:
ClockThread *clock_thread;
};
#endif
cpp 文件
cat *.cpp
#include "clockthread.h"
ClockThread::ClockThread(QObject *parent)
:QThread(parent)
{
}
void ClockThread::run()
{
while(m_thread_runing)
{
emit sigReady();
sleep(1);
}
}
void ClockThread::set_thread_runing(bool thread_runing)
{
m_thread_runing = thread_runing;
}
#include <QApplication>
#include "mainw.h"
int main(int argc,char *argv[])
{
QApplication app(argc,argv);
MainWindow mainw;
mainw.show();
return app.exec();
}
#include "mainw.h"
#include "clockthread.h"
MainWindow::MainWindow(QWidget *parent):QMainWindow(parent)
{
clock_thread = new ClockThread(this);
connect(clock_thread, SIGNAL(sigReady()), this, SLOT(slot_updateClock()));
clock_thread->start();
}
MainWindow::~MainWindow()
{
//如果析构函数为空,当然会有
//QThread: Destroyed while thread is still running
//已放弃
//如果不停止线程而wait, 会卡死.
clock_thread->set_thread_runing(false);
//停止了线程,必须等待线程结束, 否则也会有
//QThread: Destroyed while thread is still running
//已放弃
clock_thread->wait();
//这句delete 倒是可有可无的,不会内存泄露,此处不加
//MainWindow 的析构中会调用delete, 因为clock_thread 是MainWindow 的子对象
delete clock_thread;
}
void MainWindow::slot_updateClock()
{
printf("update.\n");
}
pro 文件
cat test_thread.pro
######################################################################
# Automatically generated by qmake (3.1) Wed Mar 2 09:34:42 2022
######################################################################
TEMPLATE = app
TARGET = test_thread
INCLUDEPATH += .
QT+=widgets
# You can make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# Please consult the documentation of the deprecated API in order to know
# how to port your code away from it.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
# Input
HEADERS += clockthread.h mainw.h
SOURCES += clockthread.cpp main.cpp mainw.cpp
|