Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a dummy lock to std::condition_variable_any::wait

Suppose there are three threads A, B, and C. B and C suspend at a certain point, waiting for A to signal them to continue. Among the thread synchronization facilities provided by standard C++, std::condition_variable seems to best fit in here (though still bad). Since std::condition_variable must be used with a lock, the code for B and C may contain lines like:

{
  std::mutex mut;
  std::unique_lock<std::mutex> lock(mut);
  cond_var.wait(lock);  // cond_var is a global variable of type std::condition_variable`
}

Note that mut is used here not for synchronization purposes at all, but just to fit the signature of std::condition_variable::wait. With this observation, I'm thinking that maybe we can do better by implementing a dummy lock class, let's say dummy_lock, and replace std::condition_variable with std::condition_variable_any. dummy_lock meets the BasicLockable requirements with all its methods essentially doing nothing. Thereby, we get code similar to the following:

{
  dummy_lock lock;
  cond_var.wait(lock);  // cond_var is a global variable of type std::condition_variable_any`
}

This, if works at all, should be of higher efficiency than the original one. But the question is, does it even work according to the standard (language-lawyers are apt here)? Even if it works, this is by-no-means an elegant solution. So, do any of you folks have better ideas?

like image 816
Lingxi Avatar asked Oct 19 '22 14:10

Lingxi


1 Answers

You are working on a false premise.

The mutex does not only protect the condition predicate, it also protects the condition_variable itself.

So the mutex should be at the same scope as the condition_variable and all locks should lock that same mutex.

like this:

// global scope
std::mutex mut;
std::condition_variable cond_var;

// thread scope
{
  std::unique_lock<std::mutex> lock(mut);
  cond_var.wait(lock);
}

see here: Why do pthreads’ condition variable functions require a mutex?

like image 59
Richard Hodges Avatar answered Oct 22 '22 21:10

Richard Hodges