当前位置:网站首页>[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 . |
边栏推荐
- "Actbert" Baidu & Sydney University of technology proposed actbert to learn the global and local video text representation, which is effective in five video text tasks!
- APP页面分享口令Rails实现
- Web side defense Guide
- [shutter] shutter custom fonts (download TTF fonts | pubspec.yaml configure font resources | synchronize resources | globally apply fonts | locally apply fonts)
- Redis distributed lock failure, I can't help but want to burst
- Web侧防御指南
- 【剑指 Offer】57. 和为s的两个数字
- 技术人创业:失败不是成功,但反思是
- 使用 EMQX Cloud 实现物联网设备一机一密验证
- Daily book - low code you must understand in the era of digital transformation
猜你喜欢

How to prevent your jar from being decompiled?

情感计算与理解研究发展概述

From personal heroes to versatile developers, the era of programmer 3.0 is coming

New feature of go1.18: trylock, which has been tossed n times

scrcpy这款软件解决了和同事分享手机屏幕的问题| 社区征文

New feature of go1.18: introduce new netip Network Library
![[shutter] shutter resource file use (import resource pictures | use image resources)](/img/e9/94ae2e3ee315f490eb3cf14bcf2e49.jpg)
[shutter] shutter resource file use (import resource pictures | use image resources)

Tencent three sides: in the process of writing files, the process crashes, and will the file data be lost?

From "bronze" to "King", there are three secrets of enterprise digitalization

Pointer and string
随机推荐
Lightgbm principle and its application in astronomical data
How to prevent your jar from being decompiled?
【剑指 Offer】56 - I. 数组中数字出现的次数
Ransack combined condition search implementation
App page sharing password rails implementation
PHP微信抢红包的算法
ServiceMesh主要解决的三大痛点
VIM command-t plugin error: unable to load the C extension - VIM command-t plugin error: could not load the C extension
pip安裝whl文件報錯:ERROR: ... is not a supported wheel on this platform
【剑指 Offer 】56 - II. 数组中数字出现的次数 II
发现你看不到的物体!南开&武大&ETH提出用于伪装目标检测SINet,代码已开源!...
SQL必需掌握的100个重要知识点:使用游标
From "bronze" to "King", there are three secrets of enterprise digitalization
Image segmentation using pixellib
【剑指 Offer】57. 和为s的两个数字
Servicemesh mainly solves three pain points
分享一下如何制作专业的手绘电子地图
20220702-程序员如何构建知识体系?
Pyqt picture decodes and encodes and loads pictures
[shutter] shutter custom fonts (download TTF fonts | pubspec.yaml configure font resources | synchronize resources | globally apply fonts | locally apply fonts)