0

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);
}
seccpur
  • 4,996
  • 2
  • 13
  • 21
  • Can you please add more information? `foo:insert` is a syntax error. Which of the two are called in 2 separate threads, ... – Rakete1111 Sep 22 '16 at 15:26
  • Unless they both depend on each other, I wouldn't think so. Can you show us the full class? – kirbyfan64sos Sep 22 '16 at 15:26
  • 1
    mutex is not re-entrant in conforming C++ library implementations. So yes. Use recursive_mutex instead. – Hans Passant Sep 22 '16 at 15:28
  • @HansPassant Could use [`recursive_mutex`](http://en.cppreference.com/w/cpp/thread/recursive_mutex) though no? TBH I'm not sure why the vector part needs to lock since the single element overload does. – Borgleader Sep 22 '16 at 15:30
  • Typing from .mobile sucks. I have edited typos. – seccpur Sep 22 '16 at 15:31
  • 1
    If the mutex is nonrecursive, this [seems to be UB](http://stackoverflow.com/questions/11173532/why-is-locking-a-stdmutex-twice-undefined-behaviour). – Ami Tavory Sep 22 '16 at 15:32
  • The two lock_guards are not overlapping. They would if the second insert called the first one, but this is not the case – Ionel POP Sep 22 '16 at 16:12
  • Yeah question edited. Difficulty typing from mobile – seccpur Sep 22 '16 at 16:23

1 Answers1

1

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

Matt Timmermans
  • 53,709
  • 3
  • 46
  • 87