当前位置:网站首页>Qtthread, one of many methods of QT multithreading
Qtthread, one of many methods of QT multithreading
2022-07-07 06:12:00 【Wen teased to death】
QThread It seems to be a very difficult thing , Especially signals and slots . The following is only a simple case written during my study .
QThread How to use multithreading
QThread Class provides a platform independent method of managing threads . stay Qt The main purpose of establishing threads in is to use threads to deal with those time-consuming background operations , For example, a large number of operations , Copy big files , Network transmission, etc .
Use Qt Framework when developing applications , Use QThread Class can easily and quickly create and manage multithreads .
Communication between multiple threads can also be used Qt Peculiar “ The signal - Slot ” Mechanism realization .
QThread There are two ways to use :
- Inherit QThread class
- QObject::moveToThread()
Inherit QThread Method
The first method is simple , It's easy to understand , Write a class inheritance QThread class , And rewrite run() function , And generate a ChildThread Example , And call the object's start() function .
Interface (.h):
#ifndef THREADDLG_H
#define THREADDLG_H
#include <QDialog>
#include <QPushButton>
#include "workthread.h"
#define MAXSIZE 5 //MAXSIZE The macro defines the number of threads
class ThreadDlg : public QDialog
{
Q_OBJECT
public:
ThreadDlg(QWidget *parent = 0);
~ThreadDlg();
private:
QPushButton *startBtn;
QPushButton *stopBtn;
QPushButton *quitBtn;
workThread *myThread[MAXSIZE]; // Create thread pointer array
public slots:
void slotStart(); // The slot function is used to start the thread
void slotStop(); // The slot function is used to terminate the thread
};
#endif // THREADDLG_H
Interface (.cpp):
#include "threaddlg.h"
#include <QHBoxLayout>
ThreadDlg::ThreadDlg(QWidget *parent)
: QDialog(parent)
{
setWindowTitle(tr(" Threads "));
startBtn = new QPushButton(tr(" Start "));
stopBtn = new QPushButton(tr(" stop it "));
quitBtn = new QPushButton(tr(" sign out "));
QHBoxLayout *mainLayout = new QHBoxLayout(this);
mainLayout->addWidget(startBtn);
mainLayout->addWidget(stopBtn);
mainLayout->addWidget(quitBtn);
connect(startBtn,SIGNAL(clicked()),this,SLOT(slotStart()));
connect(stopBtn,SIGNAL(clicked()),this,SLOT(slotStop()));
connect(quitBtn,SIGNAL(clicked()),this,SLOT(close()));
}
void ThreadDlg::slotStart()
{
for(int i=0;i<MAXSIZE;i++)
{
myThread[i]=new workThread(); // Create five threads
}
for(int i=0;i<MAXSIZE;i++)
{
myThread[i]->start(); // Start these five threads
}
startBtn->setEnabled(false);
stopBtn->setEnabled(true);
}
void ThreadDlg::slotStop()
{
for(int i=0;i<MAXSIZE;i++)
{
myThread[i]->terminate();// End these five threads
myThread[i]->wait();// Blocking waiting for processing to end
}
startBtn->setEnabled(true);
stopBtn->setEnabled(false);
}
ThreadDlg::~ThreadDlg()
{
}
Thread class :(.h)
#ifndef WORKTHREAD_H
#define WORKTHREAD_H
#include <QThread>
class workThread:public QThread
{
public:
workThread();
protected:
void run();
};
#endif // WORKTHREAD_H
If you want the main thread to pass parameters to the child thread , Constructors can be used to interact with data .
Thread class :(.cpp)
#include "workthread.h"
#include <QDebug>
#include <QVector>
workThread::workThread()
{
}
void workThread::run()
{
QVector<int> nums{
1,2,4,3,6,4,2,2,23434,554,232,323,54,66};
int n = nums.size();
bool isChange = false;
while (true) {
for(int i = 1;i<n;i++){
for(int j = 0;j<n-i-1;j++){
if(nums[j]>nums[j+1])
{
int t = nums[j];
nums[j] = nums[j+1];
nums[j+1] = t;
isChange = true;
}
}
if(!isChange){
break;
}
}
for(int &n:nums){
qDebug()<<n<<" ";
}
}
}
QObject::moveToThread
To be honest, I don't quite understand this method
- Define an ordinary QObject Derived class FileWorker, And then the object move To QThread in .
- Defining a forwarding class is also QObject Subclass , It's called controller, Or call it dummy. The signal slot of the forwarding class and FileWorker Class , In this way, the slot function of the forwarding class is called in the main thread , Or receive the signal OK 了 .
It probably means through the forwarding class , Can make FileWorker The slot function of class runs properly in the sub thread . At the same time, there is no need to use QMutex To synchronize ,Qt The event loop will automatically handle this .
summary
Recommended :
stay QThread Subclasses add signals . It's absolutely safe , And it's true ( The thread dependency of the sender doesn't matter )
What should not be done is :
call moveToThread(this) function
Specify connection type : This usually means that you are doing the wrong thing , For example, will QThread The control interface is mixed with the business logic ( This should be placed in a separate object of the thread )
stay QThread Subclass add slot function : This means that they will be called on the wrong thread , That is to say QThread The thread of the object , instead of QThread Object managed threads . This requires you to specify the connection type or call moveToThread(this) function
Use QThread::terminate() function
What cannot be done is :
Exit the program while the thread is still running . Use QThread::wait() Function waits for the thread to end
stay QThread Destroy the object while the thread managed by the object is still running . If you need something “ Self destruction ” The operation of , You can take finished() The signal is the same as deleteLater() Slots connected
Reference resources :https://blog.csdn.net/zb872676223/article/details/22718087
边栏推荐
- MFC BMP sets the resolution of bitmap, DPI is 600 points, and gdiplus generates labels
- Understand the deserialization principle of fastjson for generics
- jmeter 函数助手 — — 随机值、随机字符串、 固定值随机提取
- Go语学习笔记 - gorm使用 - gorm处理错误 | Web框架Gin(十)
- Senior programmers must know and master. This article explains in detail the principle of MySQL master-slave synchronization, and recommends collecting
- 关于STC单片机“假死”状态的判别
- Experience of Niuke SQL
- C note 13
- How much do you know about clothing ERP?
- Input of native applet switches between text and password types
猜你喜欢
Check point: the core element for enterprises to deploy zero trust network (ztna)
PowerPivot - DAX (function)
Go语学习笔记 - gorm使用 - gorm处理错误 | Web框架Gin(十)
[FPGA tutorial case 14] design and implementation of FIR filter based on vivado core
你不知道的互联网公司招聘黑话大全
Go language learning notes - Gorm use - native SQL, named parameters, rows, tosql | web framework gin (IX)
从“跑分神器”到数据平台,鲁大师开启演进之路
Industrial Finance 3.0: financial technology of "dredging blood vessels"
Interview skills of software testing
苹果cms V10模板/MXone Pro自适应影视电影网站模板
随机推荐
Find duplicate email addresses
POI excel export, one of my template methods
JVM监控及诊断工具-命令行篇
[InstallShield] Introduction
Why does the data center need a set of infrastructure visual management system
Cf:c. column swapping [sort + simulate]
ML之shap:基于adult人口普查收入二分类预测数据集(预测年收入是否超过50k)利用shap决策图结合LightGBM模型实现异常值检测案例之详细攻略
Senior programmers must know and master. This article explains in detail the principle of MySQL master-slave synchronization, and recommends collecting
win系统下安装redis以及windows扩展方法
Ten stages of becoming a Senior IC Design Engineer. What stage are you in now?
Go语学习笔记 - gorm使用 - 原生sql、命名参数、Rows、ToSQL | Web框架Gin(九)
Check Point:企业部署零信任网络(ZTNA)的核心要素
Vscode for code completion
yarn入门(一篇就够了)
你不知道的互联网公司招聘黑话大全
蚂蚁庄园安全头盔 7.8蚂蚁庄园答案
DC-7靶机
linear regression
Jstat of JVM command: View JVM statistics
Personal imitation SSM framework