C++ hierarchical_mutex 层次锁

class hierarchical_mutex{
  private:

    std::mutex internal_mutex;
  
    unsigned long const hierarchy_value;
    unsigned long previous_hierarchy_value;
   
    // thread_local
    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 updata_hierarchy_value(){
        previous_hierarchy_value = this_thread_hierarchy_value;
        this_thread_hierarchy_value = hierarchy_value;
    }
    
public:

    explicit hierarchical_mutex(unsigned long value):
        hierarchy_value(value),
        previous_hierarchy_value(0)
    {}
    
    void lock(){
        check_for_hierarchy_violation();
        internal_mutex.lock();
        updata_hierarchy_value();
    }

    void unlock(){
        this_thread_hierarchy_value = previous_hierarchy_value;
        internal_mutex.unlock();
    }

    bool try_lock(){
        check_for_hierarchy_violation();
        if(!internal_mutex.try_lock()){
            return false;
        }
        updata_hierarchy_value();
        return true;
    }
};
// 初始化 类静态本地线程变量
thread_local unsigned long hierarchical_mutex::this_thread_hierarchy_value(ULONG_MAX);

你可能感兴趣的:(C++,c++)