8099999,青筋妹,内蒙古财税职业学院
例子:lock_guard的模板类hierarchical_mutex
class hierarchical_mutex{ std::mutex mtx; unsigned long const hcl_val; unsigned long pre_hcl_val; static thread_local unsigned long this_hcl_val; void check_for_hcl_violaction(){ if(this_hcl_val <= hcl_val){ throw std::logic_error("mutex hierarchy violated"); } } void update_hierarchy_value(){ pre_hcl_val = this_hcl_val; this_hcl_val = hcl_val; } public: explicit hierarchical_mutex(unsigned long val): hcl_val(val), pre_hcl_val(0){} void lock(){ check_for_hcl_violaction(); mtx.lock(); update_hierarchy_value(); } void unlock(){ this_hcl_val = pre_hcl_val; mtx.unlock(); } bool try_lock(){ check_for_hcl_violaction(); if(!mtx.try_lock()) return false; update_hierarchy_value(); return true; } };
顺序锁的应用例子:当要锁定时某个锁时,要先检查已经上锁的锁的序号,如果序号低于现在要锁的锁的序号的话就可以锁定,否则,抛出异常。
我也没理解锁的序号的真正含义,只是做个记录,抄一个例子。。。
#include <mutex> #include <climits>//ulong_max #include <thread> class hierarchical_mutex{ std::mutex mtx; unsigned long const hcl_val; unsigned long pre_hcl_val; static thread_local unsigned long this_hcl_val; void check_for_hcl_violaction(){ if(this_hcl_val <= hcl_val){ throw std::logic_error("mutex hierarchy violated"); } } void update_hierarchy_value(){ pre_hcl_val = this_hcl_val; this_hcl_val = hcl_val; } public: explicit hierarchical_mutex(unsigned long val): hcl_val(val), pre_hcl_val(0){} void lock(){ check_for_hcl_violaction(); mtx.lock(); update_hierarchy_value(); } void unlock(){ this_hcl_val = pre_hcl_val; mtx.unlock(); } bool try_lock(){ check_for_hcl_violaction(); if(!mtx.try_lock()) return false; update_hierarchy_value(); return true; } }; thread_local unsigned long hierarchical_mutex::this_hcl_val(ulong_max); hierarchical_mutex high_level_mutex(10000); hierarchical_mutex low_level_mutex(5000); int do_low_level_stuff(){ return 1; } int low_level_func(){ std::lock_guard<hierarchical_mutex> lk(low_level_mutex); return do_low_level_stuff(); } void high_level_stuff(int param){ } void high_level_func(){ std::lock_guard<hierarchical_mutex> lk(high_level_mutex); high_level_stuff(low_level_func()); } void thread_a(){ high_level_func(); } hierarchical_mutex other_mutex(100); void do_other_stuff(){ } void other_stuff(){ high_level_func(); do_other_stuff(); } void thread_b(){ std::lock_guard<hierarchical_mutex> lk(other_mutex); other_stuff(); } int main(){ //锁定顺序合法(因为先锁的大的,后锁的小的) std::thread a(thread_a); //锁定顺序非法(因为先锁的小的,后锁的大的) std::thread b(thread_b); a.join(); b.join(); }
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
如何在没有core文件的情况下用dmesg+addr2line定位段错误
用QT制作3D点云显示器——QtDataVisualization
网友评论