当前位置:网站首页>挂起等待锁 vs 自旋锁(两者的使用场合)
挂起等待锁 vs 自旋锁(两者的使用场合)
2022-07-05 05:21:00 【abs(ln(1+NaN))】
1、自旋锁的定义
挂起等待锁:当某个线程没有申请到锁的时候,此时该线程会被挂起,即加入到等待队列等待。当锁被释放的时候,就会被唤醒,重新竞争锁
自旋锁:当某个线程没有申请到锁的时候,该线程不会被挂起,而是每隔一段时间检测锁是否被释放。如果锁被释放了,那就竞争锁;如果没有释放,过一会儿再来检测。
2、自旋锁相关函数
Linux提供了一种数据类型来表示自旋锁 —— pthread_spinlock_t
(1) 加锁/解锁函数
(2) 初始化/销毁函数
3、挂起等待锁、自旋锁的使用场景
既然如此,那什么时候应该用自旋锁,什么时候使用挂起等待锁呢?
例子1:你约好你朋友一起去打球,你朋友说要一个小时准备好,于是乎,你就去附近的网吧玩了一个小时打发时间。
例子2:同样是你约朋友去打球,你朋友说5分钟准备好,于是你就在楼下等,每隔1分钟给你朋友发送消息询问情况。
例子1 ——》 挂起等待锁,当临界区运行的时间较长时,我们一般使用挂起等待锁。我们先让线程PCB加入到等待队列中等待,等锁被释放时,再重新申请锁。
例子2 ——》自旋锁,如果这里使用挂起等待锁,可能线程刚加入等待队列,锁就被释放了,将线程唤醒是需要成本的。因此,当临界区运行的时间较短时,我们一般使用自旋锁。
边栏推荐
- Remote upgrade afraid of cutting beard? Explain FOTA safety upgrade in detail
- Bucket sort
- 2022 / 7 / 1 Résumé de l'étude
- 【ES实战】ES上的native realm安全方式使用
- [allocation problem] 455 Distribute cookies
- Introduction to memory layout of FVP and Juno platforms
- 被舆论盯上的蔚来,何时再次“起高楼”?
- Ue4/ue5 illusory engine, material part (III), material optimization at different distances
- 动漫评分数据分析与可视化 与 IT行业招聘数据分析与可视化
- Web APIs DOM节点
猜你喜欢
Yolov5 ajouter un mécanisme d'attention
On-off and on-off of quality system construction
YOLOv5添加注意力机制
Double pointer Foundation
Embedded database development programming (zero)
SAP-修改系统表数据的方法
Generate filled text and pictures
Research on the value of background repeat of background tiling
[to be continued] [depth first search] 547 Number of provinces
Web APIs DOM节点
随机推荐
Heap sort summary
To the distance we have been looking for -- film review of "flying house journey"
《动手学深度学习》学习笔记
Pointnet++学习
Remote upgrade afraid of cutting beard? Explain FOTA safety upgrade in detail
SAP-修改系统表数据的方法
Grail layout and double wing layout
Find a good teaching video for Solon framework test (Solon, lightweight application development framework)
PMP candidates, please check the precautions for PMP examination in July
Simple modal box
[merge array] 88 merge two ordered arrays
lxml.etree.XMLSyntaxError: Opening and ending tag mismatch: meta line 6 and head, line 8, column 8
Warning using room database: schema export directory is not provided to the annotation processor so we cannot export
动漫评分数据分析与可视化 与 IT行业招聘数据分析与可视化
[转]MySQL操作实战(一):关键字 & 函数
【ES实战】ES上的native realm安全方式使用
Kali 2018 full image download
A new micro ORM open source framework
Stm32cubemx (8): RTC and RTC wake-up interrupt
64 horses, 8 tracks, how many times does it take to find the fastest 4 horses at least