当前位置:网站首页>挂起等待锁 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 ——》自旋锁,如果这里使用挂起等待锁,可能线程刚加入等待队列,锁就被释放了,将线程唤醒是需要成本的。因此,当临界区运行的时间较短时,我们一般使用自旋锁。
边栏推荐
- [to be continued] [UE4 notes] L3 import resources and project migration
- YOLOv5添加注意力機制
- Simple HelloWorld color change
- Es module and commonjs learning notes
- 小程序直播+電商,想做新零售電商就用它吧!
- Shell Sort
- [binary search] 34 Find the first and last positions of elements in a sorted array
- [binary search] 69 Square root of X
- 搭建完数据库和网站后.打开app测试时候显示服务器正在维护.
- A three-dimensional button
猜你喜欢

On-off and on-off of quality system construction

JVM call not used once in ten years
![[to be continued] [UE4 notes] L2 interface introduction](/img/0f/268c852b691bd7459785537f201a41.jpg)
[to be continued] [UE4 notes] L2 interface introduction

BUUCTF MISC

YOLOv5-Shufflenetv2
![[turn to] MySQL operation practice (III): table connection](/img/70/20bf9b379ce58761bae9955982a158.png)
[turn to] MySQL operation practice (III): table connection

Applet live + e-commerce, if you want to be a new retail e-commerce, use it!

Web APIs DOM node

YOLOv5添加注意力机制

Stm32cubemx (8): RTC and RTC wake-up interrupt
随机推荐
使用命令符关闭笔记本自带键盘命令
cocos2dx_ Lua card flip
Haut OJ 1221: a tired day
[to be continued] [UE4 notes] L2 interface introduction
64 horses, 8 tracks, how many times does it take to find the fastest 4 horses at least
Solon Logging 插件的添加器级别控制和日志器的级别控制
Solon 框架如何方便获取每个请求的响应时间?
搭建完数据库和网站后.打开app测试时候显示服务器正在维护.
使用Room数据库报警告: Schema export directory is not provided to the annotation processor so we cannot expor
[turn]: Apache Felix framework configuration properties
2022 / 7 / 1 Résumé de l'étude
动漫评分数据分析与可视化 与 IT行业招聘数据分析与可视化
Web APIs DOM node
[binary search] 34 Find the first and last positions of elements in a sorted array
Magnifying glass effect
Ue4/ue5 illusory engine, material part (III), material optimization at different distances
远程升级怕截胡?详解FOTA安全升级
[turn]: OSGi specification in simple terms
质量体系建设之路的分分合合
2022年上半年国家教师资格证考试