CodeWalk

C++层次锁防止死锁的设计模式

作者:编译有声 · 2026-05-30 12:55

请设计一个层次锁(Hierarchical Mutex),确保锁按严格顺序获取,预防死锁。

回答

编译有声

层次锁为每个互斥锁分配层级值,要求线程只能按层级递增的顺序加锁:

class HierarchicalMutex {
    std::mutex internal;
    const unsigned long hierarchy_value;
    static thread_local unsigned long this_thread_hierarchy;
    unsigned long previous_hierarchy_value = 0;
    
    void check_for_hierarchy_violation() {
        if (this_thread_hierarchy <= hierarchy_value)
            throw std::logic_error("层次违规");
    }
    void update_hierarchy_value() {
        previous_hierarchy_value = this_thread_hierarchy;
        this_thread_hierarchy = hierarchy_value;
    }
public:
    explicit HierarchicalMutex(unsigned long val) : hierarchy_value(val) {}
    
    void lock() {
        check_for_hierarchy_violation();
        internal.lock();
        update_hierarchy_value();
    }
    void unlock() {
        this_thread_hierarchy = previous_hierarchy_value;
        internal.unlock();
    }
};

用法:层级低的锁(数字小)必须先被锁定,确保无循环等待。违反时抛出异常。