简体   繁体   中英

Will recursive_mutex deadlock when locked by 2 threads?

std::recursive_mutex won't deadlock when the same thread locks it multiple times.

Will it deadlock when multiple threads lock it multiple times?

Will it deadlock when multiple threads lock it multiple times?

That cannot happen.

By definition a mutex is locked by at most one thread. And a std::recursive_mutex is some kind of mutex. Otherwise it does not comply to its goal of mutual exclusion , since it should be some kind of Mutex concept .

So another thread is not even allowed to lock it a single time. When it does, that other thread stays blocked (till the lock is released - as many times as it was recursively locked).

FYI, here is a simplistic implementation of a recursive 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};
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM