当前位置: 首页 > news >正文

层级锁笔记

注意看test_hierarchy_lock函数:如果thread t2的不注释,就会报错。

这是因为层级锁 更强调单个线程内上锁的顺序。
线程t2已经获取了hmtx2,再试图获取hmtx1就会因为违反层级顺序而抛出异常。

#include <mutex>
#include <thread>
//层级锁
class hierarchical_mutex {
public:explicit hierarchical_mutex(unsigned long value) :_hierarchy_value(value),_previous_hierarchy_value(0) {}hierarchical_mutex(const hierarchical_mutex&) = delete;hierarchical_mutex& operator=(const hierarchical_mutex&) = delete;void lock() {check_for_hierarchy_violation(); // 必须_this_thread_hierarchy_value >= 待获取锁的层级值 当前层级值,才继续_internal_mutex.lock();update_hierarchy_value(); // _this_thread_hierarchy_value 变成 待获取锁的层级值}void unlock() {if (_this_thread_hierarchy_value != _hierarchy_value) {throw std::logic_error("mutex hierarchy violated");}_this_thread_hierarchy_value = _previous_hierarchy_value;_internal_mutex.unlock();}bool try_lock() {check_for_hierarchy_violation();if (!_internal_mutex.try_lock()) {return false;}update_hierarchy_value();return true;}
private:std::mutex  _internal_mutex;//当前层级值unsigned long const _hierarchy_value;//上一次层级值unsigned long _previous_hierarchy_value;//本线程记录的层级值static thread_local  unsigned long  _this_thread_hierarchy_value;void check_for_hierarchy_violation() {if (_this_thread_hierarchy_value <= _hierarchy_value) {throw  std::logic_error("mutex  hierarchy violated");}}void  update_hierarchy_value() {_previous_hierarchy_value = _this_thread_hierarchy_value;_this_thread_hierarchy_value = _hierarchy_value;}
};thread_local unsigned long hierarchical_mutex::_this_thread_hierarchy_value(ULONG_MAX);void test_hierarchy_lock() {hierarchical_mutex  hmtx1(1000);hierarchical_mutex  hmtx2(500);std::thread t1([&hmtx1, &hmtx2]() {std::this_thread::sleep_for(std::chrono::milliseconds(500));hmtx1.lock();hmtx2.lock();hmtx2.unlock();hmtx1.unlock();});std::thread t2([&hmtx1, &hmtx2]() {hmtx2.lock();
//		hmtx1.lock();
//		hmtx1.unlock();hmtx2.unlock();});t1.join();t2.join();
}int main(){test_hierarchy_lock();return 0;
}
http://www.lryc.cn/news/312872.html

相关文章:

  • 基于SpringBoot+Vue 的专家医院预约挂号系统
  • 计算机基础专升本笔记十二-Excel常用快捷键大全
  • 制作耳机壳的UV树脂和塑料材质相比优势有哪些?
  • JS(JavaScript)中如何实现,复选框checkbox多选功能
  • 直接修改zynq petalinux编译出来的rootfs.cpio.gz文件内容
  • 什么是 Golang 类型断言
  • mysql数据库root权限读写文件
  • 力扣爆刷第88天之hot100五连刷26-30
  • Ethersacn的交易数据是什么样的(2)
  • 学习Android的第二十二天
  • JavaScript——流程控制(程序结构)
  • 如何用ChatGPT+GEE+ENVI+Python进行高光谱,多光谱成像遥感数据处理?
  • AIGC工具( 7个 )
  • 学习Java的第一天
  • 【设计模式】工厂模式与抽象工厂模式
  • 使用plasmo框架开发浏览器插件,注入contents脚本和给页面添加UI组件
  • python并发 惰性处理大型数据集
  • Docker将本地的镜像上传到私有仓库
  • [LeetBook]【学习日记】有效数字——状态机
  • 学习目标2024
  • 引入js,刷新清除缓存
  • 【VSCODE修改代码行间距】解决方案
  • lvs+keepalive
  • 用spark读取及存储数据
  • 蓝牙 | 软件: Qualcomm BT Audio 问题分析(4)----检查MIPS使用情况
  • 【实战】K8S集群部署nacos并接入Springcloud项目容器化运维
  • prometheus监控zookeeper方案
  • 智能照明控制系统的优点有哪些
  • Cent OS 安装 vmware tools
  • 写一个关于RN的分秒毫秒组件(组件状态由同一个父组件控制)