ObliteratedJillo
ObliteratedJillo

Reputation: 5156

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);
}

Upvotes: 0

Views: 371

Answers (1)

Matt Timmermans
Matt Timmermans

Reputation: 59144

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

Upvotes: 1

Related Questions