当前位置:网站首页>[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 .
边栏推荐
- Find the combination number acwing 888 Find the combination number IV
- [leetcode] day94 reshape matrix
- 4. Oracle redo log file management
- Leetcode heap correlation
- 阿里巴巴成立企业数智服务公司“瓴羊”,聚焦企业数字化增长
- Leetcode-6111: spiral matrix IV
- Erreur de connexion Navicat à la base de données Oracle Ora - 28547 ou Ora - 03135
- 5. Oracle tablespace
- Sword finger offer II 058: schedule
- P2575 master fight
猜你喜欢

5. Oracle tablespace

2021apmcm post game Summary - edge detection

Day 2 document

求组合数 AcWing 889. 满足条件的01序列

栈 AcWing 3302. 表达式求值

WordPress switches the page, and the domain name changes back to the IP address

Quickly use Amazon memorydb and build your own redis memory database

1.15 - input and output system
![[wustctf2020] plain_ WP](/img/66/fdf7649359f36444703ff2279562e6.jpg)
[wustctf2020] plain_ WP

容斥原理 AcWing 890. 能被整除的数
随机推荐
Gaussian elimination acwing 884 Gauss elimination for solving XOR linear equations
C - XOR to all (binary topic)
How to make water ripple effect? This wave of water ripple effect pulls full of retro feeling
Leetcode heap correlation
JS quickly converts JSON data into URL parameters
5.Oracle-錶空間
1.14 - assembly line
Simple selection sort of selection sort
Redis-01.初识Redis
ADG5412FBRUZ-RL7应用 双电源模拟开关和多路复用器IC
How to generate an image from text on fly at runtime
[leetcode] day94 reshape matrix
Winter vacation water test 1 Summary
【LeetCode】Day95-有效的数独&矩阵置零
4.Oracle-重做日志文件管理
Find the combination number acwing 887 Find combination number III
SQL三种连接:内连接、外连接、交叉连接
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
Sqlmap tutorial (1)
Leetcode-6108: decrypt messages