当前位置:网站首页>[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 . |
边栏推荐
- [shutter] shutter opens a third-party application (url|launcher plug-in search and installation | url| launcher plug-in official example | open browser | open a third-party application)
- 一周生活
- *C language final course design * -- address book management system (complete project + source code + detailed notes)
- New feature of go1.18: trylock, which has been tossed n times
- ArrayList analysis 2: pits in ITR, listiterator, and sublist
- TinyMCE visual editor adds Baidu map plug-in
- Market Research - current situation and future development trend of preclinical medical device testing service market
- How to prevent your jar from being decompiled?
- How do I access the kubernetes API?
- Unity3D学习笔记4——创建Mesh高级接口
猜你喜欢

Reading experience of just because

TinyMCE visual editor adds Baidu map plug-in

20220702 how do programmers build knowledge systems?

Riding the wind of "cloud native" and stepping on the wave of "digitalization", new programmer 003 starts pre-sale

腾讯三面:进程写文件过程中,进程崩溃了,文件数据会丢吗?

Daily book - low code you must understand in the era of digital transformation

What is it that makes you tremble? Those without fans can learn

《ActBERT》百度&悉尼科技大学提出ActBERT,学习全局局部视频文本表示,在五个视频-文本任务中有效!

The failure rate is as high as 80%. What should we do about digital transformation?

sql service 截取字符串
随机推荐
Technological Entrepreneurship: failure is not success, but reflection is
VIM command-t plugin error: unable to load the C extension - VIM command-t plugin error: could not load the C extension
在beforeDestroy中销毁localStorage中的值无效
SQL必需掌握的100个重要知识点:使用游标
Market Research - current situation and future development trend of anti-counterfeiting label market
关于PHP-数据库的 数据读取,Trying to get property 'num_rows' of non-object?
Ransack组合条件搜索实现
ServiceMesh主要解决的三大痛點
Image segmentation using pixellib
New feature of go1.18: introduce new netip Network Library
100 important knowledge points that SQL must master: management transaction processing
LightGBM原理及天文数据中的应用
Sql service intercepts string
[001] [arm-cortex-m3/4] internal register
Market Research - current situation and future development trend of carob chocolate market
[Jianzhi offer] 56 - ii Number of occurrences of numbers in the array II
Market Research - current market situation and future development trend of third-party data platform
Attack and defense world PWN question: Echo
VictoriaMetrics 简介
Using emqx cloud to realize one machine one secret verification of IOT devices