当前位置:网站首页>[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 .
边栏推荐
猜你喜欢
Bash exercise 17 writing scripts to install the server side of FRP reverse proxy software
P2575 master fight
阿里新成员「瓴羊」正式亮相,由阿里副总裁朋新宇带队,集结多个核心部门技术团队
ollvm编译出现的问题纪录
4. Object mapping Mapster
容斥原理 AcWing 890. 能被整除的数
2.Oracle-数据文件的添加及管理
Chapter 6 relational database theory
Bit of MySQL_ OR、BIT_ Count function
5. Oracle tablespace
随机推荐
[2021]GIRAFFE: Representing Scenes as Compositional Generative Neural Feature Fields
Leetcode stack related
June 29, 2022 daily
Winter vacation water test 1 Summary
Redis-02.Redis命令
Operator priority, one catch, no doubt
Usage scenarios of golang context
2022-5-第四周日报
4. 对象映射 - Mapping.Mapster
There are three kinds of SQL connections: internal connection, external connection and cross connection
How to understand the definition of sequence limit?
Simple selection sort of selection sort
Leetcode array operation
栈 AcWing 3302. 表达式求值
如何正确在CSDN问答进行提问
2021apmcm post game Summary - edge detection
博弈论 AcWing 892. 台阶-Nim游戏
1.13 - RISC/CISC
International Open Source firmware Foundation (osff) organization
Is it impossible for lamda to wake up?