当前位置:网站首页>17.5 concept, usage, deadlock demonstration and solution of mutex
17.5 concept, usage, deadlock demonstration and solution of mutex
2022-06-11 11:22:00 【zzyzxb】
Protect shared data , In operation , A thread , Lock shared data with code , Operational data , Unlock
Other threads that operate on shared data must wait to unlock . Lock it in , operation , Unlock .
One 、 The mutex (mutex) Basic concepts of
Mutex is a class object , It's a lock , Multiple threads try to use lock() Member function to lock the lock , Only one thread can lock successfully ( Successful callouts are lock The function returns ).
If no lock succeeds , So the process card is lock() There's a constant attempt to lock this lock .
Be careful when using mutex , No more or less data can be protected , The protection effect is not achieved , Too much affects efficiency .
Two 、 The usage of mutex
<1>lock()、unlock()
First lock() Operating shared data , Again unlock()
lock() and unlock() Use in pairs , Yes lock() There must be unlock(), Every call lock(), It must be called once unlock().
Should not and should not be allowed to call 1 Time lock() But called 2 Time unlock(), It is also not allowed to call 2 Time lock() But call 1 Time unlock(),
These asymmetric numbers of calls can lead to code instability or even crash .
Yes lock(), forget unlock() The problem of , It's very difficult to investigate ;
To prevent people from forgetting unlock(), Introduce a name called std::lock_guard Class template for : You forget unlock() It doesn't matter , I'll do it for you unlock();
After learning, you can only use the pointer (unique_ptr<>): It doesn't matter if you forget to free memory , I'll set you free ; nanny
(2.2)std::lock_guard Class template : Directly replace lock() and unlock(), in other words , You use the lock_gurad after , You can't use it anymore lock() and unlock().
3、 ... and : Deadlock
Zhang San : Standing in Beijing waiting for Li Si Don't move
Li Si : Standing in Shenzhen waiting for Zhang San Don't move
C++ in , For example, I have two locks ( The problem of deadlock is caused by at least two lock heads, that is, two mutexes ), Golden Lock (JinLock), Silver lock (YinLock);
Two threads A,B
(1) Threads A When it comes to execution , This thread locks the Golden Lock first , A gold lock lock() After success , And then it goes lock() Silver lock …
A context switch appears
(2) Threads B Yes , This thread locks the silver lock first , Because the silver lock hasn't been locked yet , So the silver lock will lock() success , Threads B Want to go lock() Golden Lock …
At the moment , A deadlock is created
(3) Threads A Because I can't get the silver lock , The process doesn't work ( All the following codes can unlock the golden lock, but the process can't go on , So the golden lock cannot be unlocked )
(4) Threads B Because I can't get the golden lock , The process doesn't work ( All the following codes can unlock the silver lock, but the process can't go on , So the silver lock cannot be unlocked )
Everybody's hanging out here , wait for me , I'll be waiting for you.
(3.1) Deadlock demonstration
(3.2) The general solution to deadlock
As long as the locking order of the two mutexes is consistent, there will be no deadlock
(3.3) std::lock() Function templates : It is used to deal with multiple mutexes
Ability : Lock two or more mutexes at a time ( At least 2 individual , There is no limit ,1 One can't )
It doesn't exist because in multiple threads , There is a risk of deadlock due to the sequence of locks
std::lock(): If one of the mutexes is not locked , It's just waiting there , When all mutexes are locked , It can go down ( return ).
Either the two mutexes are locked , Either the two mutexes are not locked . If only one is locked , The other one didn't lock , Then it immediately unlocks the locked one .
(3.4) std::lock_guard Of std::lock Parameters
std::adopt_lock It's a structure object , Play a marker role , The function is to show that the mutex has lock();
Don't need to std::lock_guardstd::mutex The constructor faces mutex Object to carry out lock() 了 .
summary : std::lock(): Lock multiple mutexes at once , Use caution ( Suggest a lock ).
MXA obj;
thread send_thread(&MXA::inMsgRecvQueue, &obj);
thread recevie_thread(&MXA::outMsgRecvQueue, &obj);
send_thread.join();
recevie_thread.join();
cout << “I Love China” << endl;
return 0;
边栏推荐
- Jerry's acquisition of ble voltage detection and ADC detection inaccuracy [chapter]
- WordPress数据库缓存插件:DB Cache Reloaded
- msf cs openssl流量加密
- 2022 Health Expo, Beijing Great Health Industry Exhibition, moxibustion health exhibition, Beijing Health Service Exhibition
- WordPress站内链接修改插件:Velvet Blues Update URLs
- 想做钢铁侠?听说很多大佬都是用它入门的
- 实用WordPress插件收集(更新中)
- Digital collection system app source code
- nft数字藏品系统开发搭建流程
- AcWing 1944. Record keeping (hash, STL)
猜你喜欢
![Jerry's acquisition of ble OTA dual backup upgrade (can only be used for chips above 4mbits) [article]](/img/25/e90d23f5c3d2aa6790538b289137bf.png)
Jerry's acquisition of ble OTA dual backup upgrade (can only be used for chips above 4mbits) [article]

SurroundDepth:自监督多摄像头环视深度估计

命令模式--进攻,秘密武器

使用Labelimg制作VOC数据集或yolo数据集的入门方法

Liufan, CFO of papaya mobile, unleashes women's innovative power in the digital age

Adapter mode -- can you talk well?

(key points of software engineering review) Chapter IV overall design exercises

使用Yolov5训练自己制作的数据集,快速上手

企业微信小程序避坑指南,欢迎补充。。。

SpingBoot+Quartrz生产环境的应用支持分布式、自定义corn、反射执行多任务
随机推荐
js合并两个对象(面试题)
AcWing 1944. Record keeping (hash, STL)
UCI-HAR数据集的处理
Enterprise wechat applet pit avoidance guide, welcome to add...
想做钢铁侠?听说很多大佬都是用它入门的
NFT digital collection system development and construction process
2022 Health Expo, Beijing Great Health Industry Exhibition, moxibustion health exhibition, Beijing Health Service Exhibition
使用Yolov5训练好模型调用电脑自带摄像头时出现问题:TypeError: argument of type “int‘ is not iterable的解决方法
WordPress landing page beautification plug-in: recommended by login Designer
Iterator mode -- battlefield autumn point
Test cos HTML cache static cache plug-in
为WordPress相关日志插件增加自动缩略图功能
使用pydub修改wav文件的比特率,报错:C:\ProgramData\Anaconda3\lib\site-packages\pydub\utils.py:170: RuntimeWarning:
Installing redis in CentOS 7 environment
不做伪工作者
js面试题---箭头函数,find和filter some和every
没有财富就不能自由吗?
NFT digital collection app system construction
适配器模式--能不能好好说话?
202年最新热门收益较高的年金险产品是什么?