簡體   English   中英

recursive_mutex由2個線程鎖定時會死鎖嗎?

[英]Will recursive_mutex deadlock when locked by 2 threads?

同一線程多次將其鎖定時,std :: recursive_mutex不會死鎖。

多個線程多次鎖定它時,它將死鎖嗎?

當多個線程多次鎖定它時,它將死鎖嗎?

那不可能發生。

根據定義互斥鎖最多由一個線程鎖定。 而且std::recursive_mutex是某種互斥體。 否則,它不符合互斥的目標,因為它應該是某種Mutex概念

因此,甚至不允許另一個線程將其鎖定一次。 當這樣做時,其他線程保持阻塞狀態(直到鎖釋放-遞歸鎖定的次數)。

僅供參考,這是遞歸互斥的簡單實現:

static const std::thread_id NO_THREAD;

class recursive_mutex {
public:

    void lock() {
        auto me = std::this_thread::get_id();
        if (owner != me) {
            mtx.lock();
            owner = me;
            assert(count == 0);
        }
        count++;
    }

    void unlock() {
        auto me = std::this_thread::get_id();
        assert(owner == me);
        assert(count > 0);
        count--;
        if (count == 0) {
            owner = NO_THREAD;
            mtx.unlock();
        }
    }

private:
    std::mutex      mtx;
    std::thread::id owner;
    unsigned        count{0};
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM