seccpur seccpur - 2 months ago 16
C++ Question

Will two overlapping mutexes lead to deadlock?

Consider the following member functions. Will it lead to a deadlock?

void foo::insert(item_ptr item)
{
lock_guard<mutex> lock(mu_);
items_.insert(item);
}

void foo::insert(vector<item_ptr> items)
{
lock_guard<mutex> lock(mu_); // will this lead
// to deadlock?
for(auto item:items)
insert(item);
}

Answer

If mu_ is a std::mutex, then you have a problem. A std::mutex does not support recursive locks and cannot be locked twice by the same thread. See: http://en.cppreference.com/w/cpp/thread/mutex

IF mu_ is a std::recursive_mutex, then you have no problem. A thread can lock a recursive mutex if it already has it locked. See http://en.cppreference.com/w/cpp/thread/recursive_mutex