通过cas去实现自旋锁
flag的0表示现在没上锁,1表示已经上锁了
- static int flag{0};
- //0表示没有锁,1表示锁了
-
- int cas(int *ptr,int newp)
- {
- int old=*ptr;
- *ptr=newp;
- return old;
- }
-
- void lock()
- {
- while(cas(&flag,1)==0){
- // cout<<"lock"<
- // cout<
- }
- }
- void unlock()
- {
- flag=0;
- // cout<<"unlock"<
- }
加上个测试代码
- static int num=0;
- void test1()
- {
- lock();
- cout<<"test1 start"<
- for(int i=0;i<5;++i)
- {
- num++;
- }
- cout<<"test1 end"<
- unlock();
- }
- void test2()
- {
- lock();
- cout<<"test2 start"<
- for(int i=0;i<10;++i)
- {
- num++;
- }
- cout<<"test2 end"<
- unlock();
-
- }
- int mai
-
相关阅读:
MySQL行级锁Row-Level Locking及表锁Table-Level Locking 简介及示例
滑动窗口求解最大值
Vue学习之样式汇总
【提问募集】向世界级软件开发大师“Bob 大叔”Robert C. Martin 提出你的疑虑!
【C#/.NET】xUnit和Moq实现TDD
【LeetCode】2319. 判断矩阵是否是一个X矩阵
商城|商城小程序|基于微信小程序的智慧商城系统设计与实现(源码+数据库+文档)
C++编程良好习惯
Spring6-单元测试:JUnit
举例说明PyTorch函数torch.cat与torch.stack的区别
-
原文地址:https://blog.csdn.net/weixin_51609435/article/details/131811850