当前位置:网站首页>[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 ).
边栏推荐
- Daily book CSO advanced road first exposed
- 100 important knowledge points that SQL must master: management transaction processing
- [shutter] shutter page Jump (route | navigator | page close)
- Reading experience of just because
- [sword finger offer] 56 - I. the number of numbers in the array
- Kubernetes resource object introduction and common commands (4)
- "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!
- ServiceMesh主要解决的三大痛点
- Five message formats of OSPF
- [shutter] shutter custom fonts (download TTF fonts | pubspec.yaml configure font resources | synchronize resources | globally apply fonts | locally apply fonts)
猜你喜欢

Technical solution of vision and manipulator calibration system

Daily book -- analyze the pain points of software automation from simple to deep
![[shutter] shutter application life cycle (foreground state resumed | background state paused | inactive | component separation state detached)](/img/4c/c8dae41fc2eb18b5153cf36861fc7d.jpg)
[shutter] shutter application life cycle (foreground state resumed | background state paused | inactive | component separation state detached)

20220702-程序员如何构建知识体系?

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

C language, to achieve three chess games

VictoriaMetrics 简介

Blue Bridge Cup Winter vacation homework (DFS backtracking + pruning)

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

540. Single element in ordered array
随机推荐
将 EMQX Cloud 数据通过公网桥接到 AWS IoT
How do I access the kubernetes API?
Promise optimized callback hell
Introduction to the principle of geographical detector
VIM command-t plugin error: unable to load the C extension - VIM command-t plugin error: could not load the C extension
An overview of the development of affective computing and understanding research
《Just because》阅读感受
Technical solution of vision and manipulator calibration system
Servicemesh mainly solves three pain points
Share how to make professional hand drawn electronic maps
"New programmer 003" was officially launched, and the cloud native and digital practical experience of 30+ companies such as Huawei and Alibaba
B.Odd Swap Sort(Codeforces Round #771 (Div. 2))
SQL必需掌握的100个重要知识点:管理事务处理
关于PHP-数据库的 数据读取,Trying to get property 'num_rows' of non-object?
【剑指 Offer】56 - I. 数组中数字出现的次数
[zero foundation I] Navicat download link
App page sharing password rails implementation
[shutter] shutter application life cycle (foreground state resumed | background state paused | inactive | component separation state detached)
一周生活
Bridge emqx cloud data to AWS IOT through the public network