当前位置:网站首页>[QT] QT multithreading development - four methods to realize multithreading design
[QT] QT multithreading development - four methods to realize multithreading design
2022-07-02 22:26:00 【iriczhao】
Qt— Use Qt Four ways to realize multithreading design
List of articles
- Qt— Use Qt Four ways to realize multithreading design
- One 、 Write it at the front
- Two 、【 Method 1 】 QThread: Bottom layer with optional event loops API
- 3、 ... and 、【 Method 2 】 QThreadPool and QRunnable: Reuse threads
- Four 、【 Method 3 】Qt Concurrent : Use advanced API
- 5、 ... and 、【 Method four 】 WorkerScript:QML Threading in
- 6、 ... and 、 How to choose the solutions of the above four different multithreading designs
- 7、 ... and 、Qt Multithreaded application design example
One 、 Write it at the front
The content of this article is : About Qt Designed for multithreaded applications .
stay Qt There are four methods for multithreading programming and design . Reasonably select the corresponding methods to meet the application scenarios in the actual development .
Two 、【 Method 1 】 QThread: Bottom layer with optional event loops API
QThread
yes Qt The basis of all threaded controls in , Every QThread An instance represents and controls a thread . Use QThread There are two ways to create a thread :1)、 You can directly instantiate and create ,2) You can also subclass it for thread creation .
1、 Instantiation QThread: Provides a parallel event loop , Allow calls to... In worker threads QObject Slot function .
2、 Inherit QThread: Allows applications to initialize new threads before starting an event loop , Or run parallel code without event loops .
3、 ... and 、【 Method 2 】 QThreadPool and QRunnable: Reuse threads
The cost of creating and destroying threads frequently can be high . To reduce the cost , You can reuse existing threads for new tasks .QThreadPool
Is reusable QThreads
Set .
To be in QThreadPool Running code in a thread of , It needs to be realized again QRunnable::run() And instantiate subclassed QRunnable
.
Use ````QThreadPool::start()``` take QRunnable Put it in QThreadPool In the running queue of . When threads are available ,QRunnable::run() The code in will execute in this thread .
【 remarks 】: Every Qt Applications all have one Global thread pool , Can pass QThreadPool::globalInstance() Visit it . This global thread pool is based on CPU The number of cores in will automatically maintain the optimal number of threads . however , In actual development , You can also explicitly create and manage a separate QThreadPool
.
Four 、【 Method 3 】Qt Concurrent : Use advanced API
Qt The concurrency module provides many advanced functions , It is used to deal with some common parallel computing modes . for example :map
、filter
and reduce
.Qt Concurrency and usage QThread
and QRunnable
Different , These functions do not need to use the underlying thread primitives , Such as mutual exclusion or semaphores . contrary , They return a QFuture
object , This object can be used to automatically retrieve the result of the function when the thread is ready or completed ;QFuture
It can also be used to query 、 Calculate progress and pause / recovery / Cancel the calculation . For convenience ,QFutureWatcher
It is allowed to communicate with QFutures
Interact .
Qt Concurrent Parallel computing model :map
、filter
and reduce
Wait for the algorithm to automatically allocate the calculation to all available processor cores , therefore , The application we write today will continue to be expanded and used when it is deployed to systems with more kernels , It's very convenient .
This module also provides QtConcurrent::run()
function , It can run any function in another thread . however ,QtConcurrent::run()
Only support map
、filter
and reduce
A subset of features available for functions ,QFuture It can be used to retrieve the return value of the function and check whether the thread is running .
however , Yes QtConcurrent::run()
The call of uses only one thread , It can't be suspended / recovery / Cancel , You cannot query the process .
5、 ... and 、【 Method four 】 WorkerScript:QML Threading in
WorkerScript
QML Type allows JavaScript Code and the GUI Threads running in parallel . Every WorkerScript An instance can be attached .js Script . call WorkerScript.sendMessage()
when , The script will be in a separate thread ( And individual QML Context ) Run in . When the script finishes running , It can send a reply back GUI Threads , This thread will call WorkerScript.onMessage()
Signal processing program .
Use WorkerScript
It's similar to using... That has been moved to another thread worker QObject, Data is transmitted between threads through signals .
【 notes 】 This method QML Use in
6、 ... and 、 How to choose the solutions of the above four different multithreading designs
As shown above ,Qt It provides different solutions for developing multithreaded applications . The right solution for multithreaded applications depends on : The purpose of the new thread and the life cycle of the thread . Here is Qt Comparison of several multithreading mechanisms :
Serial number | characteristic | QThread | QRunnable and QThreadPool | QtConcurrent::run() | Qt Concurrent(Map/Filter/Reduce) | WorkerScript |
---|---|---|---|---|---|---|
1 | development language | C++ | C++ | C++ | C++ | QML |
2 | Whether thread priority can be specified | Yes | Yes | |||
3 | Whether a thread can run an event loop | Yes | ||||
4 | Threads receive data updates through signals | Yes (received by a worker QObject) | Yes (received by WorkerScript) | |||
5 | Whether threads can use signals to control | Yes (received by QThread) | Yes (received by QFutureWatcher) | |||
6 | Whether the thread can pass QFuture To monitor | In part | Yes | |||
7 | Whether it has built-in capabilities : Cancel / Pause / recovery | Yes | ||||
7、 ... and 、Qt Multithreaded application design example
Thread life cycle | operation | resolvent |
---|---|---|
One call | Run a new linear function in another thread , You can choose to update the progress during operation . | Qt Provides different solutions : Put this function in QThread::run() Re implementation of , And start the QThread. Signal to update progress . Put this function in QRunnable::run() Re implementation of , And will QRunnable Add to QThreadPool in . Write thread safe variables to update progress . Use QtConcurrent:: Run() Operation function . Write thread safe variables to update progress . |
One call | Run an existing function in another thread and get its return value . | Use QtConcurrent:: Run() Operation function . Give Way QFutureWatcher When the function returns finished() The signal , And call QFutureWatcher::result() To get the return value of the function . |
One call | Run an existing function in another thread and get its return value . | Use QtConcurrent:: Run() Operation function . Give Way QFutureWatcher When the function returns finished() The signal , And call QFutureWatcher::result() To get the return value of the function . |
One call | Use all available kernel pair containers (Container) All the items of the perform operations . for example , Generate thumbnails from the image list . | Use QtConcurrent Of QtConcurrent::filter() Function to select container elements , Use QtConcurrent::map() Function to apply an operation to each element . To convert the output into a single result , have access to QtConcurrent:: filteredreduce() and QtConcurrent::mappedReduced(). |
One call / Forever | In pure QML Complete the calculation of growth time in the application , And update when the results are ready GUI. | Put the calculation code in .js Script , And attach it to WorkerScript example . call WorkerScript.sendMessage() Start the calculation in a new thread . Let the script call sendMessage(), Pass the result back to GUI Threads . stay onMessage Process the results in and update them there GUI. |
Forever | There is an object in another thread , It can perform different tasks according to the request , also / Or you can receive new data to process . | Subclass a QObject To create a worker. Instantiate this worker Object and a QThread. take worker Move to new thread . Connect to... Through queued signals and slots worker Object to send commands or data . |
Forever | Repeat expensive operations in another thread , The thread does not need to receive any signals or events . | Directly in QThread::run() Write infinite loop in the re implementation of . Start the thread without an event loop . Let the thread signal to send data back GUI Threads . |
边栏推荐
- 攻防世界pwn题:Recho
- Reading experience of just because
- : last child does not take effect
- Market Research - current market situation and future development trend of night vision goggles for pilots
- Daily book -- analyze the pain points of software automation from simple to deep
- Market Research - current market situation and future development trend of marine wet exhaust hose
- Market Research - current situation and future development trend of carob chocolate market
- ServiceMesh主要解决的三大痛點
- Landingsite eband B1 smoke test case
- Basic concepts of image and deep understanding of yuv/rgb
猜你喜欢
Daily book CSO advanced road first exposed
Blue Bridge Cup Winter vacation homework (DFS backtracking + pruning)
The failure rate is as high as 80%. What should we do about digital transformation?
Gee: (II) resampling the image
A specially designed loss is used to deal with data sets with unbalanced categories
The book "new programmer 002" is officially on the market! From "new database era" to "software defined car"
tinymce可视化编辑器增加百度地图插件
Redis distributed lock failure, I can't help but want to burst
"New programmer 003" was officially launched, and the cloud native and digital practical experience of 30+ companies such as Huawei and Alibaba
Interpretation of CVPR paper | generation of high fidelity fashion models with weak supervision
随机推荐
Market Research - current situation and future development trend of marine clutch Market
The failure rate is as high as 80%. What should we do about digital transformation?
Market Research - current market situation and future development trend of intravenous injection (IV) bottles
技术人创业:失败不是成功,但反思是
:last-child 不生效解决
The difference between include < > and include ""
如何访问kubernetes API?
kubernetes资源对象介绍及常用命令(四)
[shutter] shutter application life cycle (foreground state resumed | background state paused | inactive | component separation state detached)
Market Research - current situation and future development trend of carob chocolate market
Lightgbm principle and its application in astronomical data
Tencent three sides: in the process of writing files, the process crashes, and will the file data be lost?
发现你看不到的物体!南开&武大&ETH提出用于伪装目标检测SINet,代码已开源!...
《ActBERT》百度&悉尼科技大学提出ActBERT,学习全局局部视频文本表示,在五个视频-文本任务中有效!
ServiceMesh主要解决的三大痛点
Market Research - current market situation and future development trend of genome editing mutation detection kit
Micro service gateway selection, please accept my knees!
Secondary development of ANSYS APDL: post processing uses command flow to analyze the result file
phpcms实现订单直接支付宝支付功能
Meibeer company is called "Manhattan Project", and its product name is related to the atomic bomb, which has caused dissatisfaction among Japanese netizens