【QT线程学习】
QT学习点滴积累之线程二
- Qt线程
Qt线程
Qt线程比较难掌握,一般都会说到两种使用方式 重载QThread,重写Run,重载QObject,MovetoThread,重写started槽函数网络文章也很多,罗列一些浏览过的网文供参考。
QT大佬的怒吼
两种使用实例
线程同步
线程还有很多内容,除了上面提到的外,还有QRunable,QFuture,线程池等等,小编也搞不懂,想从应用的角度去模拟出来一种或者两种模式。
从应用场景看,线程大概会出现如下场景:
运行耗时运算,通讯发送完等待返回,平时休眠触发运行,时间片运行。
未完待续,后面陆续记录下来。
上一篇学习了使用QObject,这一章记录继承QThread的学习内容。
还是以两种使用实例提供的例子进行学习,后面提供修改验证的例子。
#ifndef MYTHREAD_H
#define MYTHREAD_H#include <QThread>class MyThread : public QThread
{Q_OBJECT
public:explicit MyThread(QObject *parent = nullptr);protected:void run();signals:// 自定义信号, 传递数据void curNumber(int num);public slots:
};#endif // MYTHREAD_H
#include "mythread.h"
#include <QDebug>MyThread::MyThread(QObject *parent) : QThread(parent)
{}void MyThread::run()
{qDebug() << "当前线程对象的地址: " << QThread::currentThread();int num = 0;while(1){emit curNumber(num++);if(num == 10000000){break;}QThread::usleep(1);}qDebug() << "run() 执行完毕, 子线程退出...";
}
这里的退出run函数,是否和前面一样没有退出线程呢?
我们和前面一样,添加一个按钮来看这个线程的是否退出。下面就是mainwindow的代码。
#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QMainWindow>QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MyThread;
class MainWindow : public QMainWindow
{Q_OBJECTpublic:MainWindow(QWidget *parent = nullptr);~MainWindow();private slots:void on_pushButton_clicked();private:Ui::MainWindow *ui;
private:MyThread* subThread;
};
#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "mythread.h"
#include <QDebug>MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow)
{ui->setupUi(this);qDebug() << "主线程对象地址: " << QThread::currentThread();// 创建子线程subThread = new MyThread;connect(subThread, &MyThread::curNumber, this, [=](int num){ui->label->setNum(num);});connect(ui->startBtn, &QPushButton::clicked, this, [=](){// 启动子线程subThread->start();});}MainWindow::~MainWindow()
{delete ui;
}void MainWindow::on_pushButton_clicked()
{ui->label_2->setNum(subThread->isFinished());
}
经过验证,线程确实退出了。
目前理解如下:
线程还是一个函数,QT进行了封装,封装成了一个类对象。
有了这些基本概念,在开始学习一下线程同步,等同步学习完,设计我们自己想要的类,处理各种场景。