当前位置:网站首页>[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 ).
边栏推荐
- 关于PHP-数据库的 数据读取,Trying to get property 'num_rows' of non-object?
- LandingSite eBand B1冒烟测试用例
- 《Just because》阅读感受
- Riding the wind of "cloud native" and stepping on the wave of "digitalization", new programmer 003 starts pre-sale
- How to write a good program when a big book speaks every day?
- Ransack组合条件搜索实现
- 基于ASP.net的手机销售管理系统(二手手机销售管理系统)+ASP.NET+C#语言+VS2010+数据库可以用于课设、毕设学习
- Unity3D学习笔记4——创建Mesh高级接口
- Market Research - current market situation and future development trend of high tibial osteotomy plate
- Bridge emqx cloud data to AWS IOT through the public network
猜你喜欢

如何访问kubernetes API?

LightGBM原理及天文数据中的应用

Find objects you can't see! Nankai & Wuhan University & eth proposed sinet for camouflage target detection, and the code has been open source

【零基础一】Navicat下载链接

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

Pip install whl file Error: Error: … Ce n'est pas une roue supportée sur cette plateforme

Five message formats of OSPF

Landingsite eband B1 smoke test case

What "real skills" should a million year old cloud native developer master? Alibaba, Tencent, meituan and byte decrypt together

Error in PIP installation WHL file: error: is not a supported wheel on this platform
随机推荐
sql service 截取字符串
Market Research - current situation and future development trend of sickle cell therapy Market
[staff] Sibelius 7.5.1 score software installation (software download | software installation)
"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!
"New programmer 003" was officially launched, and the cloud native and digital practical experience of 30+ companies such as Huawei and Alibaba
【剑指 Offer】57. 和为s的两个数字
Off chip ADC commissioning record
技术人创业:失败不是成功,但反思是
[leetcode] sword finger offer 11 Rotate the minimum number of the array
Record the functions of sharing web pages on wechat, QQ and Weibo
Bridge emqx cloud data to AWS IOT through the public network
Pip install whl file Error: Error: … Ce n'est pas une roue supportée sur cette plateforme
Market Research - current situation and future development trend of cell-based seafood market
:last-child 不生效解决
[shutter] shutter gesture interaction (small ball following the movement of fingers)
[leetcode] sword finger offer 04 Search in two-dimensional array
ArrayList分析2 :Itr、ListIterator以及SubList中的坑
Find objects you can't see! Nankai & Wuhan University & eth proposed sinet for camouflage target detection, and the code has been open source
一周生活
Market Research - current market situation and future development trend of aircraft audio control panel system