Medicine
Medicine

Reputation: 2023

Why is this C++11 program not going to deadlock?

#include <iostream>
#include <mutex>

using namespace std;

int main()
{
    mutex m;
    m.lock();
    cout << "locked once\n";

    m.lock();
    cout << "locked twice\n";

    return 0;
}

Output:

./a.out 
locked once
locked twice

Doesn't the program needs to deadlock at the point of second lock i.e. a mutex being locked twice by same thread?

Upvotes: 1

Views: 40

Answers (1)

MrTux
MrTux

Reputation: 33993

If lock is called by a thread that already owns the mutex, the behavior is undefined: the program may deadlock, or, if the implementation can detect the deadlock, a resource_deadlock_would_occur error condition may be thrown.

http://en.cppreference.com/w/cpp/thread/mutex/lock

Upvotes: 2

Related Questions