Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 Can I ensure a condition_variable.wait() won't miss a notification?

I have thread 1 executing the following code:

unique_lock<mutex> ul(m);
while(condition == true)
    cv.wait(ul);

And thread 2 executing this code:

condition = false;
cv.notify_one();

Unfortunately I'm hitting a timing issue:

T1: condition checks true
                            T2: condition set to false
                            T2: cv.notify_one()
T1: cv.wait()

Thread 1 misses the notification completely and remains blocked on wait(). I tried using the version of wait() which takes a predicate but with essentially the same result. That is, the body of the predicate performs the check, but before it returns, the condition's value is changed and the notification is sent. The predicate then returns.

How can I fix this?

like image 841
screwnut Avatar asked Jul 29 '12 02:07

screwnut


People also ask

What does condition_variable wait do in C++?

std::condition_variable wait causes the current thread to block until the condition variable is notified or a spurious wakeup occurs, optionally looping until some predicate is satisfied. 1) Atomically unlocks lock, blocks the current executing thread, and adds it to the list of threads waiting on *this.

How can a thread wait on a condition variable?

Explanation: When you want to sleep a thread, condition variable can be used. In C under Linux, there is a function pthread_cond_wait () to wait or sleep. On the other hand, there is a function pthread_cond_signal () to wake up sleeping or waiting thread. Threads can wait on a condition variable.

Should you be aware of these issues of condition variables?

You should be aware of these issues of condition variables. The C++ core guideline CP 42 just states: "Don't wait without a condition". Wait! Condition variables support a quite simple concept. One thread prepares something and sends a notification another thread is waiting for. Why can't this be so dangerous?

Can you wait without a condition in C++?

The C++ core guideline CP 42 just states: "Don't wait without a condition". Wait! Condition variables support a quite simple concept. One thread prepares something and sends a notification another thread is waiting for. Why can't this be so dangerous? Okay, let's start with the only rule for today.


1 Answers

You should fix this race condition by having thread 2 lock the condition's mutex before changing the flag.

You are describing a typical race condition that happens for unprotected flags and conditions. These race conditions are the reason for the mutex lock pattern in condition usage. Put simply, always have a mutex protect the variables involved in checking a condition value.

In code for thread 2:

unique_lock<mutex> ul(m);
condition = false;
cv.notify_one();
like image 68
thiton Avatar answered Oct 25 '22 11:10

thiton