当前位置:网站首页>[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
WorkerScriptQML 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 . |
边栏推荐
- The failure rate is as high as 80%. What should we do about digital transformation?
- Micro service gateway selection, please accept my knees!
- Using emqx cloud to realize one machine one secret verification of IOT devices
- Pip install whl file Error: Error: … Ce n'est pas une roue supportée sur cette plateforme
- Record the functions of sharing web pages on wechat, QQ and Weibo
- 20220702 how do programmers build knowledge systems?
- Scrcpy this software solves the problem of sharing mobile screen with colleagues | community essay solicitation
- Blue Bridge Cup Eliminate last one (bit operation, code completion)
- Une semaine de vie
- 【leetcode】1380. Lucky number in matrix
猜你喜欢

Reading experience of just because

Landingsite eband B1 smoke test case
![[shutter] shutter custom fonts (download TTF fonts | pubspec.yaml configure font resources | synchronize resources | globally apply fonts | locally apply fonts)](/img/27/8594ba0b49d5008b7469967babed17.jpg)
[shutter] shutter custom fonts (download TTF fonts | pubspec.yaml configure font resources | synchronize resources | globally apply fonts | locally apply fonts)

An overview of the development of affective computing and understanding research

Pointer and string

phpcms实现订单直接支付宝支付功能

LandingSite eBand B1冒烟测试用例

The source code of the daily book analyzes the design idea of Flink and solves the problems in Flink

Redis distributed lock failure, I can't help but want to burst

*C语言期末课程设计*——通讯录管理系统(完整项目+源代码+详细注释)
随机推荐
A specially designed loss is used to deal with data sets with unbalanced categories
How to center the positioned text horizontally and vertically
App page sharing password rails implementation
A week's life
An overview of the development of affective computing and understanding research
C语言,实现三子棋小游戏
Redis distributed lock failure, I can't help but want to burst
[leetcode] sword finger offer 04 Search in two-dimensional array
Blue Bridge Cup Winter vacation homework (DFS backtracking + pruning)
TinyMCE visual editor adds Baidu map plug-in
Market Research - current market situation and future development trend of marine wet exhaust hose
Lightgbm principle and its application in astronomical data
Market Research - current situation and future development trend of sickle cell therapy Market
Necessary browser plug-ins for network security engineers
kubernetes资源对象介绍及常用命令(四)
[shutter] shutter application life cycle (foreground state resumed | background state paused | inactive | component separation state detached)
Chargement de l'image pyqt après décodage et codage de l'image
How to prevent your jar from being decompiled?
Market Research - current market situation and future development trend of aircraft wireless intercom system
From "bronze" to "King", there are three secrets of enterprise digitalization