当前位置:网站首页>挂起等待锁 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 ——》自旋锁,如果这里使用挂起等待锁,可能线程刚加入等待队列,锁就被释放了,将线程唤醒是需要成本的。因此,当临界区运行的时间较短时,我们一般使用自旋锁。
边栏推荐
- [轉]: OSGI規範 深入淺出
- 使用Room数据库报警告: Schema export directory is not provided to the annotation processor so we cannot expor
- 远程升级怕截胡?详解FOTA安全升级
- Haut OJ 1321: mode problem of choice sister
- [turn]: Apache Felix framework configuration properties
- sync.Mutex源码解读
- Ue4/ue5 illusory engine, material chapter, texture, compression and memory compression and memory
- UE fantasy engine, project structure
- Vs2015 secret key
- 服务熔断 Hystrix
猜你喜欢

Download and use of font icons

【论文笔记】Multi-Goal Reinforcement Learning: Challenging Robotics Environments and Request for Research

2022年上半年国家教师资格证考试

小程序直播+電商,想做新零售電商就用它吧!

第六章 数据流建模—课后习题

Web APIs DOM node
![[to be continued] [depth first search] 547 Number of provinces](/img/c4/b4ee3d936776dafc15ac275d2059cd.jpg)
[to be continued] [depth first search] 547 Number of provinces

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

Use of snippets in vscode (code template)

2022/7/2 question summary
随机推荐
Introduction to tools in TF-A
Pointnet++的改进
Stm32cubemx (8): RTC and RTC wake-up interrupt
动漫评分数据分析与可视化 与 IT行业招聘数据分析与可视化
小程序直播+电商,想做新零售电商就用它吧!
YOLOv5添加注意力机制
对象的序列化
A complete attack chain
[sum of two numbers] 169 sum of two numbers II - enter an ordered array
How can the Solon framework easily obtain the response time of each request?
win10虚拟机集群优化方案
Use of snippets in vscode (code template)
GBase数据库助力湾区数字金融发展
2022/7/1 learning summary
[interval problem] 435 Non overlapping interval
记录QT内存泄漏的一种问题和解决方案
Haut OJ 1347: addition of choice -- high progress addition
使用Room数据库报警告: Schema export directory is not provided to the annotation processor so we cannot expor
2022 / 7 / 1 Résumé de l'étude
Introduction to memory layout of FVP and Juno platforms