Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost::condition_variable and lock

boost::condition_variable cond;
boost::mutex mut;

//thread1
{
"read_socket()"
cond.notify_one();
}

//thread2
{
for(;;)
{
...
boost::unique_lock<boost::mutex> lock(mut);
cond.wait(lock);
}
}

versus

boost::condition_variable cond;
boost::mutex mut;

//thread1
{
"read_socket()"
boost::unique_lock<boost::mutex> lock(mut);
cond.notify_one();
}

//thread2
{
for(;;)
{
...
boost::unique_lock<boost::mutex> lock(mut);
cond.wait(lock);
}

Is there an impact if I omit the lock before calling cond.notify_one() ?

like image 866
Guillaume Paris Avatar asked Dec 16 '25 15:12

Guillaume Paris


1 Answers

The C++11 standard does not state any requirement for notify_one and notify_all; so not holding the lock when you signal a condition_variable is fine. However, it's often necessary for the signaling thread to hold the lock until it sets the condition checked by the waiting thread after it's woken up. If it does not, the program may contain races. For an example, see this SO question: Boost synchronization.

like image 54
Alexey Kukanov Avatar answered Dec 19 '25 05:12

Alexey Kukanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!