当前位置:网站首页>[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 . |
边栏推荐
- SQL必需掌握的100个重要知识点:管理事务处理
- From personal heroes to versatile developers, the era of programmer 3.0 is coming
- 如何访问kubernetes API?
- App page sharing password rails implementation
- ServiceMesh主要解决的三大痛点
- A specially designed loss is used to deal with data sets with unbalanced categories
- Reading experience of just because
- Ransack组合条件搜索实现
- Ransack combined condition search implementation
- Introduction to the principle of geographical detector
猜你喜欢
*C language final course design * -- address book management system (complete project + source code + detailed notes)
Error in PIP installation WHL file: error: is not a supported wheel on this platform
《Just because》阅读感受
[shutter] shutter gesture interaction (click event handling | click OnTap | double click | long press | click Cancel | press ontapdown | lift ontapup)
Micro service gateway selection, please accept my knees!
Hanoi Tower problem
What is it that makes you tremble? Those without fans can learn
Scrcpy this software solves the problem of sharing mobile screen with colleagues | community essay solicitation
phpcms实现订单直接支付宝支付功能
kubernetes资源对象介绍及常用命令(四)
随机推荐
Interpretation of CVPR paper | generation of high fidelity fashion models with weak supervision
Market Research - current market situation and future development trend of aircraft front wheel steering system
Secondary development of ANSYS APDL: post processing uses command flow to analyze the result file
《ActBERT》百度&悉尼科技大学提出ActBERT,学习全局局部视频文本表示,在五个视频-文本任务中有效!
B.Odd Swap Sort(Codeforces Round #771 (Div. 2))
将 EMQX Cloud 数据通过公网桥接到 AWS IoT
[Jianzhi offer] 57 And are two numbers of S
Necessary browser plug-ins for network security engineers
一周生活
The failure rate is as high as 80%. What should we do about digital transformation?
一周生活
Learn computer knowledge from scratch
[Jianzhi offer] 56 - ii Number of occurrences of numbers in the array II
100 important knowledge points that SQL must master: using cursors
[leetcode] sword finger offer 04 Search in two-dimensional array
GEE:(二)对影像进行重采样
[shutter] shutter page Jump (route | navigator | page close)
Pointer and string
Find objects you can't see! Nankai & Wuhan University & eth proposed sinet for camouflage target detection, and the code has been open source
Sql service intercepts string