当前位置:网站首页>[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 high tibial osteotomy plate
- pyqt图片解码 编码后加载图片
- APP页面分享口令Rails实现
- Pyqt picture decodes and encodes and loads pictures
- :last-child 不生效解决
- Necessary browser plug-ins for network security engineers
- 将 EMQX Cloud 数据通过公网桥接到 AWS IoT
- Secondary development of ANSYS APDL: post processing uses command flow to analyze the result file
- Market Research - current situation and future development trend of anterior cruciate ligament (ACL) reconstruction Market
- Unity3D学习笔记4——创建Mesh高级接口
猜你喜欢

Scrcpy this software solves the problem of sharing mobile screen with colleagues | community essay solicitation

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

Technical solution of vision and manipulator calibration system

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

TinyMCE visual editor adds Baidu map plug-in

Daily book CSO advanced road first exposed

Introduction to victoriametrics
![[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)](/img/f7/cb41d159e5c5ef3f4f1b9468d52ccc.jpg)
[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)

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

pip安裝whl文件報錯:ERROR: ... is not a supported wheel on this platform
随机推荐
Daily book CSO advanced road first exposed
pyqt圖片解碼 編碼後加載圖片
图像基础概念与YUV/RGB深入理解
[Jianzhi offer] 57 And are two numbers of S
关于测试用例
[C question set] of V
B.Odd Swap Sort(Codeforces Round #771 (Div. 2))
Web侧防御指南
ServiceMesh主要解决的三大痛点
Find objects you can't see! Nankai & Wuhan University & eth proposed sinet for camouflage target detection, and the code has been open source
Tencent three sides: in the process of writing files, the process crashes, and will the file data be lost?
20220702-程序员如何构建知识体系?
"New programmer 003" was officially launched, and the cloud native and digital practical experience of 30+ companies such as Huawei and Alibaba
Blue Bridge Cup Eliminate last one (bit operation, code completion)
PHP微信抢红包的算法
How to center the positioned text horizontally and vertically
【C 题集】of Ⅴ
Off chip ADC commissioning record
Market Research - current situation and future development trend of marine clutch Market
Unity3d learning notes 4 - create mesh advanced interface