当前位置:网站首页>挂起等待锁 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 ——》自旋锁,如果这里使用挂起等待锁,可能线程刚加入等待队列,锁就被释放了,将线程唤醒是需要成本的。因此,当临界区运行的时间较短时,我们一般使用自旋锁。
边栏推荐
- Use of room database
- Transport connection management of TCP
- Insert sort
- [turn]: Apache Felix framework configuration properties
- A three-dimensional button
- Count sort
- C language Essay 1
- Haut OJ 1245: large factorial of CDs --- high precision factorial
- [to be continued] I believe that everyone has the right to choose their own way of life - written in front of the art column
- win下一键生成当日的时间戳文件
猜你喜欢
![[interval problem] 435 Non overlapping interval](/img/a3/2911ee72635b93b6430c2efd05ec9a.jpg)
[interval problem] 435 Non overlapping interval

object serialization
![[转]MySQL操作实战(三):表联结](/img/70/20bf9b379ce58761bae9955982a158.png)
[转]MySQL操作实战(三):表联结

UE fantasy engine, project structure
![[to be continued] [UE4 notes] L1 create and configure items](/img/20/54ba719be2e51b7db5b7645b361e26.jpg)
[to be continued] [UE4 notes] L1 create and configure items

Fragment addition failed error lookup

Ue4/ue5 illusory engine, material chapter, texture, compression and memory compression and memory

Django reports an error when connecting to the database. What is the reason

Shell Sort
![[to be continued] [UE4 notes] L2 interface introduction](/img/0f/268c852b691bd7459785537f201a41.jpg)
[to be continued] [UE4 notes] L2 interface introduction
随机推荐
Fragment addition failed error lookup
[merge array] 88 merge two ordered arrays
cocos2dx_ Lua card flip
Learning notes of "hands on learning in depth"
Research on the value of background repeat of background tiling
Stm32cubemx (8): RTC and RTC wake-up interrupt
Unity ugui source code graphic
Embedded database development programming (zero)
SAP-修改系统表数据的方法
2022/7/2 question summary
object serialization
A complete attack chain
Do a small pressure test with JMeter tool
嵌入式数据库开发编程(五)——DQL
[speed pointer] 142 circular linked list II
Add level control and logger level control of Solon logging plug-in
Web APIs DOM node
To the distance we have been looking for -- film review of "flying house journey"
Zheng Qing 21 ACM is fun. (3) part of the problem solution and summary
Simple modal box