7

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?

ks1322
  • 33,961
  • 14
  • 109
  • 164
screwnut
  • 1,367
  • 7
  • 26
  • 1
    Is it really necessary to have both a boolean value you are checking, and a condition variable? Couldn't you just wait on the condition variable? – Vaughn Cato Jul 29 '12 at 02:58
  • This code was greatly simplified. (Forgot to mention. Sorry.) Checking and setting the condition involved more than just loading/flipping a boolean. In fact, I believe the bug was easier to notice because it was taking a non-negligible amount of time to deal with the condition. – screwnut Jul 29 '12 at 06:33
  • 1
    @VaughnCato No. A cv can only be used **with an actual variable**. – curiousguy Jul 29 '12 at 06:33

2 Answers2

8

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();
thiton
  • 35,651
  • 4
  • 70
  • 100
0

You have a data race because of the conflicting read/write access to condition. This implies that the behavior of your program is not defined.

The race condition on cv is the least of your worries: the program could do anything!

curiousguy
  • 8,038
  • 2
  • 40
  • 58