Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 202
SSteven Avatar asked Feb 10 '26 08:02

SSteven


2 Answers

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).

like image 141
Basile Starynkevitch Avatar answered Feb 16 '26 06:02

Basile Starynkevitch


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};
};
like image 39
Solomon Slow Avatar answered Feb 16 '26 06:02

Solomon Slow