当前位置:网站首页>[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 .
边栏推荐
- LeetCode 0107. Sequence traversal of binary tree II - another method
- One question per day 1020 Number of enclaves
- MySQL advanced part 2: SQL optimization
- Game theory acwing 891 Nim games
- 2022-5-the fourth week daily
- Leetcode-3: Longest substring without repeated characters
- Bash exercise 17 writing scripts to install the server side of FRP reverse proxy software
- Liunx starts redis
- Find the combination number acwing 887 Find combination number III
- 中国剩余定理 AcWing 204. 表达整数的奇怪方式
猜你喜欢
3.Oracle-控制文件的管理
[2020]GRAF: Generative Radiance Fields for 3D-Aware Image Synthesis
How to make water ripple effect? This wave of water ripple effect pulls full of retro feeling
Paper reading report
什么是套接字?Socket基本介绍
Gauss Cancellation acwing 884. Solution d'un système d'équations Xor linéaires par élimination gaussienne
Suppose a bank's ATM machine, which allows users to deposit and withdraw money. Now there is 200 yuan in an account, and both user a and user B have the right to deposit and withdraw money from this a
4. Oracle redo log file management
Sqlmap tutorial (1)
Open source storage is so popular, why do we insist on self-development?
随机推荐
June 29, 2022 daily
Daily question 1189 Maximum number of "balloons"
MySQL advanced part 2: optimizing SQL steps
博弈论 AcWing 891. Nim游戏
Traversal of leetcode tree
What is socket? Basic introduction to socket
求组合数 AcWing 887. 求组合数 III
[moviepy] unable to find a solution for exe
Simple selection sort of selection sort
Erreur de connexion Navicat à la base de données Oracle Ora - 28547 ou Ora - 03135
5. Oracle tablespace
Redis publish subscribe command line implementation
在新线程中使用Handler
论文阅读报告
博弈论 AcWing 892. 台阶-Nim游戏
MySQL advanced part 1: index
International Open Source firmware Foundation (osff) organization
Filter the numbers and pick out even numbers from several numbers
In depth analysis of for (VaR I = 0; I < 5; i++) {settimeout (() => console.log (I), 1000)}
[leetcode] day95 effective Sudoku & matrix zeroing