当前位置:网站首页>[QT] QT multithreading development qthread
[QT] QT multithreading development qthread
2022-07-05 06:25:00 【iriczhao】
List of articles
One 、QThread Two ways to use
QThread
yes Qt The core classes used to run code in different threads , It is QObject Subclasses of
About QThread How to use ,Qt Officials offer two ways :
(1-1) Method 1
Step one : To create a new thread that executes some code , Subclass QThread And re implement run()
Step two : Then create an instance of the subclass and call start() Running threads
The following code snippet :
class MyThread : public QThread {
private:
void run() override {
// Code to run in a new thread
}
};
MyThread *thread = new MyThread;
thread->start(); // call run() Start a new thread
// ...
thread->wait(); // Wait for the thread to complete
Thread has priority , You can specify it as an optional parameter start(), Or use setPriority() change .
When from run() return ( After a while ) The thread will stop running , The specific length of time is related to the operating system .
QThread::isRunning()
and QThread::isFinished()
Provides information about thread execution , You can get the running state of the thread through these two member functions .
QThread
Yes QThread::started() and QThread::finished() Two signals .
A thread can call QThread:sleep() Function temporarily stops execution . Usually this is an inappropriate method of use , But more event driven ( Or poll ) It's much better .
Through to QThread call wait() To wait for the thread execution to complete , The maximum number of milliseconds to wait for optional directional function delivery .
(1-2) Method 2
Second use QThread establish 、 Methods of managing threads : It is not derived in essence QThread 了 . Steps are as follows :
(1) establish QThread
(2) Use moveToThread()
Add objects to QThread Managed threads .
The following code snippet :
auto thread = new QThread;
auto worker = new Worker;
connect(thread, &QThread::started, worker, &Worker::doWork);
connect(worker, &Worker::workDone, thread, &QThread::quit);
connect(thread, &QThread::finished, worker, &Worker::deleteLater);
worker->moveToThread(thread);
thread->start();
QThread The second way to use , Allows us to run code in other threads without subclassing QThread.
Two 、Qt Two strategies of thread running
There are two basic strategies for running code in threads : No event loop
and With event loop
(1) No event loop
Derived class QThread And overloading QThread::run()
Member functions . Create an instance and use QThread::start()
Start a new thread .
class MyThread : public QThread {
private:
void run() override {
loadFilesFromDisk();
doCalculations();
saveResults();
}
};
auto thread = new MyThread;
thread->start();
thread->wait();
(2) With event loop
When dealing with timers 、 The Internet 、 Queuing signal / Slot link and other problems , Event cycling is necessary .
Qt Support single thread event loop , As shown in the figure below :
The local event loop of each thread is QObjects
Delivery events , If there is no event loop , Objects that exist in the corresponding thread will not receive events .
By means of run() Call in QThread::exec()
To start the thread's local event loop . The following code snippet :
class MyThread : public QThread {
private:
void run() override {
auto socket = new QTcpSocket;
socket->connectToHost(...);
exec(); // Run the event loop
// Perform some cleanup operations
}
};
QThread::quit()
or QThread::exit()
Will exit the event loop . have access to QEventLoop Or call it manually QCoreApplication::processEvents().
notes :QThread::run() The default implementation of actually calls QThread: exec (). If overloaded QThread::run(), We have to call it manually QThread: exec ()
.
3、 ... and 、QThread Precautions for use of
The following four types of operations cannot be performed in a non main thread :
(1) Execute on GUI Control operation . Including but not limited to : Use any QWidget / Qt Quick / QPixmap API; Use QImage, QPainter etc. , Yes. ; Use OpenGL It may be possible : But call at run time QOpenGLContext: supportsThreadedOpenGL ()
Necessary inspection .
(2) Cannot call Application::exec().
(3) After destroying the corresponding QThread
Before the object , Be sure to destroy all in the secondary thread QObject.【 This is very important 】.
(4) Don't block. GUI Threads .
How to ensure QObjects Destroyed ? as follows :
(1) stay QThread::run() Create... On the stack QObject
.
(2) Put their QObject::deleteLater()
The slot function is connected to QThread::finished()
The signal .
(3) hold QObject
Move out of the thread .
For example, the following code snippet :
class MyThread : public QThread {
private:
void run() override {
MyQObject obj1, obj2, obj3;
QScopedPointer<OtherQObject> p;
if (condition)
p.reset(new OtherQObject);
auto anotherObj = new AnotherQObject;
connect(this, &QThread::finished,anotherObj, &QObject::deleteLater);
auto yetAnother = new YetAnotherQObject;
// Before exiting the thread , Move the object into the main thread
yetAnother->moveToThread(qApp->thread());
// Notify the main thread about this object in some way ,
// So it can be deleted .
// From this line of code , Don't use or operate on this QObject!
}
};
Four 、 summary
Qt Under the development of multithreading , Use QThread
It's more convenient . This article records the use of QThread Two methods of , as well as QThread Event delivery mode of thread running in , Also record about QThread Some do's and don 'ts .
边栏推荐
- MySQL advanced part 1: index
- MySQL advanced part 2: SQL optimization
- JS quickly converts JSON data into URL parameters
- 论文阅读报告
- Sorting out the latest Android interview points in 2022 to help you easily win the offer - attached is the summary of Android intermediate and advanced interview questions in 2022
- 高斯消元 AcWing 884. 高斯消元解异或線性方程組
- WordPress switches the page, and the domain name changes back to the IP address
- Bash exercise 17 writing scripts to install the server side of FRP reverse proxy software
- Single chip computer engineering experience - layered idea
- FFmpeg build下载(包含old version)
猜你喜欢
5. Oracle TABLESPACE
Find the combination number acwing 889 01 sequence meeting conditions
2.Oracle-数据文件的添加及管理
容斥原理 AcWing 890. 能被整除的数
Bit of MySQL_ OR、BIT_ Count function
What is socket? Basic introduction to socket
博弈论 AcWing 892. 台阶-Nim游戏
阿里新成员「瓴羊」正式亮相,由阿里副总裁朋新宇带队,集结多个核心部门技术团队
Simple selection sort of selection sort
WordPress switches the page, and the domain name changes back to the IP address
随机推荐
Leetcode backtracking method
Ffmpeg build download (including old version)
ADG5412FBRUZ-RL7应用 双电源模拟开关和多路复用器IC
1.手动创建Oracle数据库
【高德地图POI踩坑】AMap.PlaceSearch无法使用
Regulations for network security events of vocational group in 2022 Guizhou Vocational College skill competition
2021apmcm post game Summary - edge detection
our solution
In depth analysis of for (VaR I = 0; I < 5; i++) {settimeout (() => console.log (I), 1000)}
博弈论 AcWing 894. 拆分-Nim游戏
博弈论 AcWing 893. 集合-Nim游戏
博弈论 AcWing 891. Nim游戏
Usage scenarios of golang context
Series of how MySQL works (VIII) 14 figures explain the atomicity of MySQL transactions and the principle of undo logging
什么是套接字?Socket基本介绍
Day 2 document
2048 project realization
Leetcode-1200: minimum absolute difference
LeetCode-61
求组合数 AcWing 888. 求组合数 IV