当前位置:网站首页>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;
边栏推荐
- Split data - horizontal split and vertical split
- 使用Yolov5训练自己制作的数据集,快速上手
- IIHS tsp+ annual safety list released: 7 EVs were selected, and there are common problems in pedestrian AEB
- nft数字藏品系统开发搭建流程
- 企业微信小程序避坑指南,欢迎补充。。。
- Jerry's ble spp open pin_ Code function [chapter]
- MWC 2022 lights up the future, and everything serves
- Distance measurement - Euclidean distance
- Package component series - (I) - slots and dynamic components
- 17.4创建多个线程、数据共享问题分析与案例代码
猜你喜欢

Lifeifei: I am more like a scientist in physics than an engineer

不做伪工作者

An introduction to creating VOC datasets or Yolo datasets using labelimg

李飞飞:我更像物理学界的科学家,而不是工程师|深度学习崛起十年

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

Package component series - (I) - slots and dynamic components

Surrounddepth: self supervised multi camera look around depth estimation

設置默認收貨地址【項目 商城】

Xiao P weekly Vol.08

Cap theory sounds very big, but it's actually very simple
随机推荐
Command mode - attack, secret weapon
Writing the program into the microcontroller can control the forward and reverse rotation of the motor more conveniently and quickly
Shi Yigong: I was not interested in research until I graduated from my doctor's degree! I'm confused about the future, and I don't know what to do in the future
Digital collection system app source code
The first day of the new year | at 8:00 p.m. tomorrow, pulsar Chinese developer and user group meeting registration
Only when you find your own advantages can you work tirelessly and get twice the result with half the effort!
在WordPress媒体库中创建文件夹
Don't be a fake worker
MWC 2022 lights up the future, and everything serves
Using domestic MCU (national technology n32g031f8s7) to realize pwm+dma control ws2812
34. find the first and last positions of elements in the sorted array ●●
WordPress数据库缓存插件:DB Cache Reloaded
CPU负载怎么理解
Where is it safer to open an account for soda ash futures? How much capital is needed to buy soda ash futures?
Characteristics and classification of creation mode (single case, factory)
Application of volatile in single chip microcomputer
National multi-year solar radiation spatial distribution data 1981-2022, temperature distribution data, evapotranspiration data, evaporation data, rainfall distribution data, sunshine data, wind speed
Appearance mode -- it has been used in various packages for a long time!
985 University doctors became popular because of their thanks in classical Chinese! The tutor commented that he not only wrote well in sci
Jerry's ble spp open pin_ Code function [chapter]