当前位置:网站首页>[QT] QT multithreading development - reentrancy and thread safety
[QT] QT multithreading development - reentrancy and thread safety
2022-07-02 22:26:00 【iriczhao】
Qt- Reentrancy and thread safety
List of articles
One 、 Write it at the front
In this article , The term " Reentrancy " and " Thread safety " Used to mark classes and functions , Show how classes and functions can be used in multithreaded applications .
Reentrancy And Thread safety These two concepts are not Qt Unique concept , They are two important technical terms in the field of multithreading .
A thread safe function can be called by multiple threads at the same time , Even if these callers will use the shared data, there will be no problem , Because access to shared data is serial (serialized)、 The protected .
A reentrant function can also be called by multiple threads at the same time , But each caller can only use its own data ( That is, only the caller's information can be used ).
therefore : A thread safe function is always reentrant , But a reentrant function is not necessarily thread safe .
To start with , A reentrant class , It means that its member functions can be called safely by multiple threads , As long as each thread uses different objects of this class . And a thread safe class , It means that its member functions can be called safely by multiple threads , Even if all threads use the same instance of this class, it doesn't matter . So : Thread safety
Of “ Security ” than Reentrant function
Of “ Security ” More secure .
【 Be careful 】 Somewhat Qt Class is designed for multithreading , Only such classes exist Qt It is marked as thread safe in the official documents . If a function is not marked Thread safety
or Reentrant
Of , It should not be used by different threads . alike , If a class is not marked thread safe or reentrant , Instances of this class should not be accessed by multiple threads .
Two 、 Reentrancy
C++ Most classes of are reentrant , This is only because they can only access their own data . Any thread can access a member function of an instance of a reentrant class , As long as no other thread can call the member function of this instance . such as , Below Counter
Classes are reentrant :
class Counter
{
public:
Counter() {
n = 0; }
void increment() {
++n; }
void decrement() {
--n; }
int value() const {
return n; }
private:
int n;
};
This class is not Thread safety
Of , Because if multiple threads try to modify members n
Words , The result is uncertain . because ++
and --
Operations are not always atomic . They are generally expanded into 3 A machine command :
1. Load variable values into registers
2. increase / Subtract the value in the register
3. Load the value in the register back into main memory
If the thread A And thread B At the same time, load the old value of the variable into the register , Increase their registers , Reload main memory , They will eventually rewrite each other , The variable is only increased once !
3、 ... and 、 Thread safety
Obviously , Yes n
The access of should be serial : Threads A Must be executed without interruption 3 A step ( Atomicity ), Then the thread B To start its steps , Or vice versa . A simple way to make a class thread safe is : Use one QMutex
To protect all access to data members . The following code :
class Counter
{
public:
Counter() {
n = 0; }
void increment() {
QMutexLocker locker(&mutex); ++n; }
void decrement() {
QMutexLocker locker(&mutex); --n; }
int value() const {
QMutexLocker locker(&mutex); return n; }
private:
mutable QMutex mutex;
int n;
};
QMutexLocker
Class is automatically locked in its constructor mutex
, And unlock in its destructor . lock mutex It ensures that the access of other threads is serialized .
mutex
Data members are declared as mutable
Of , This is because value() It's a const function , But we need to be in it lock and unlock This mutex.
( stay C++ in ,mutable
It's for a breakthrough const It's set by the limit of , Can be used to modify the member variables of a class . By mutable Decorated variable , Will always be in a state of variability , Even if it's const You can also change the value of this variable in the function )
Four 、 matters needing attention
many Qt All classes of are reentrant , But they are not thread safe , Because thread safety means locking and unlocking QMutex Add more expenses . such as :QString
It's reentrant , But it's not thread safe . You can access different from multiple threads at the same time QString
Example , But it cannot be accessed from multiple threads at the same time QString The same example of ( Unless you use QMutex
Protect access ).
边栏推荐
- Market Research - current market situation and future development trend of aircraft wireless intercom system
- [shutter] shutter gesture interaction (small ball following the movement of fingers)
- Sql service intercepts string
- Bridge emqx cloud data to AWS IOT through the public network
- PIP audit: a powerful security vulnerability scanning tool
- App page sharing password rails implementation
- 2019 Nanchang (relive the classic)
- Technological Entrepreneurship: failure is not success, but reflection is
- Web侧防御指南
- C语言,实现三子棋小游戏
猜你喜欢
How to prevent your jar from being decompiled?
《ActBERT》百度&悉尼科技大学提出ActBERT,学习全局局部视频文本表示,在五个视频-文本任务中有效!
Etcd Raft 协议
[shutter] shutter gesture interaction (click event handling | click OnTap | double click | long press | click Cancel | press ontapdown | lift ontapup)
Scrcpy this software solves the problem of sharing mobile screen with colleagues | community essay solicitation
[shutter] shutter resource file use (import resource pictures | use image resources)
Pip install whl file Error: Error: … Ce n'est pas une roue supportée sur cette plateforme
关于测试用例
《Just because》阅读感受
Share how to make professional hand drawn electronic maps
随机推荐
pyqt圖片解碼 編碼後加載圖片
VIM command-t plugin error: unable to load the C extension - VIM command-t plugin error: could not load the C extension
Servicemesh mainly solves three pain points
Try to get property'num for PHP database data reading_ rows' of non-object?
Market Research - current market situation and future development trend of genome editing mutation detection kit
How to prevent your jar from being decompiled?
Market Research - current situation and future development trend of anterior cruciate ligament (ACL) reconstruction Market
发现你看不到的物体!南开&武大&ETH提出用于伪装目标检测SINet,代码已开源!...
Kubernetes resource object introduction and common commands (4)
图像基础概念与YUV/RGB深入理解
Sql service intercepts string
Market Research - current market situation and future development trend of aircraft audio control panel system
#include<>和#include“”的区别
SQL必需掌握的100个重要知识点:使用游标
《Just because》阅读感受
VictoriaMetrics 简介
【零基础一】Navicat下载链接
New feature of go1.18: trylock, which has been tossed n times
[C question set] of V
Market Research - current market situation and future development trend of aircraft wireless intercom system