Answer to this question is wrong as it has chance to deadlock. Condition Variable - Wait/Notify Race Condition
I found no solution to solving race condition or dead lock issue.
Imagine we have two threads. now goal is as follows.
first condition:
Thread 1 Waits
Thread 2 Notifies
second condition:
Thread 2 Notifies
Thread 1 Should not wait and continue normal execution.
How can this be implemented correctly without having a queue for notifies? because I want this part of code to run as fast as possible and use a Boolean value instead of adding item into queue. Also there are only 2 threads, so use of queue seems overkill for me.
pseudo code when there is race condition:
Thread 1:
lock(x);
if(!signaled)
{
unlock(x); // ********
// still small gap, how to avoid?
cv.wait(); // forget spurious wakeup for sake of simplicity
signaled = false;
}
else // ********
unlock(x);
Thread 2:
lock(x);
signaled = true;
cv.notify();
unlock(x);
now if you remove two lines commented with ********
race condition will be solved and chance of deadlock will be introduced where Thread1 waits while owning the lock and Thread2 is stuck at locking x.