QT:QThread:重写run函数
问题描述:QThread的使用方法2重写run函数
解决:
创建一个集成QThread的类thread
thread.h:
run()
函数则是新线程的入口,run()
函数退出意味着线程的退出。
stop()函数:线程停止
#ifndef THREAD_H
#define THREAD_H
#include <QThread>
#include <iostream>
#include <QDebug>
class thread: public QThread
{
Q_OBJECT
public:
thread();
void stop();
protected:
void run();
void printMessage();
private:
volatile bool stopped;
};
#endif // THREAD_H
thread.cpp
#include "thread.h"
#include <QDebug>
thread::thread()
{
stopped =false;
}
void thread::run()
{
qDebug() << "子线程id:" << QThread::currentThreadId();
while(!stopped)
{
printMessage();
}
stopped = false;
}
void thread::stop()
{
qDebug()<<"进程已经停止";
stopped = true;
}
void thread::printMessage()
{
qDebug()<< "hello";
usleep(5);
}
mainwindow.h:两个按钮的槽函数一个是开启线程一个是关闭线程
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QThread>
#include <iostream>
#include <QDebug>
#include <QMainWindow>
#include <QCloseEvent>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
private:
Ui::MainWindow *ui;
protected:
void closeEvent(QCloseEvent *event);
};
#endif // MAINWINDOW_H
mainwindow.cpp:
closeEvent:QThread的安全销毁
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "thread.h"
thread myThread;
//thread myThread1;
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
qDebug() << "主线程id:" << QThread::currentThreadId();
}
//关闭线程
void MainWindow::on_pushButton_clicked()
{
myThread.stop();
}
//开启线程
void MainWindow::on_pushButton_2_clicked()
{
myThread.start();
}
void MainWindow::closeEvent(QCloseEvent *event)
{
myThread.stop();
myThread.wait();
event->accept();
}
MainWindow::~MainWindow()
{
delete ui;
}