简体   繁体   中英

How to fix race condition for condition variable wait/notify

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.

The source of your confusion is your misunderstanding of conditional variables. The inherent feature of them is that lock release and entering into wait mode is done atomically , ie nothing happens in between.

So no modification to the variable can be happening before variables enters into wait mode, because lock will not be released. This is basic guarantee of any conforming conditional_variable implementation, for example, here is the extract from the reference page for std::conditional_variable :

http://en.cppreference.com/w/cpp/thread/condition_variable/wait

Atomically releases lock, blocks the current executing thread, and adds it to the list of threads waiting on *this. The thread will be unblocked when notify_all() or notify_one() is executed. It may also be unblocked spuriously. When unblocked, regardless of the reason, lock is reacquired and wait exits. If this function exits via exception, lock is also reacquired. (until C++14)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM