c++ - How to fix race condition for condition variable wait/notify -
answer question wrong has chance deadlock. condition variable - wait/notify race condition
i found no solution solving race condition or dead lock issue.
imagine have 2 threads. goal follows.
first condition: thread 1 waits thread 2 notifies second condition: thread 2 notifies thread 1 should not wait , continue normal execution.
how can implemented correctly without having queue notifies? because want part of code run fast possible , use boolean value instead of adding item queue. there 2 threads, use of queue seems overkill me.
pseudo code when there race condition:
thread 1: lock(x); if(!signaled) { unlock(x); // ******** // still small gap, how avoid? cv.wait(); // forget spurious wakeup sake of simplicity signaled = false; } else // ******** unlock(x); thread 2: lock(x); signaled = true; cv.notify(); unlock(x);
now if remove 2 lines commented ********
race condition solved , chance of deadlock introduced thread1 waits while owning lock , thread2 stuck @ locking x.
the source of confusion misunderstanding of conditional variables. inherent feature of them lock release , entering wait mode done atomically, i.e. nothing happens in between.
so no modification variable can happening before variables enters wait mode, because lock not released. basic guarantee of conforming conditional_variable
implementation, example, here extract reference page std::conditional_variable
:
http://en.cppreference.com/w/cpp/thread/condition_variable/wait
atomically releases lock, blocks current executing thread, , adds list of threads waiting on *this. thread unblocked when notify_all() or notify_one() executed. may unblocked spuriously. when unblocked, regardless of reason, lock reacquired , wait exits. if function exits via exception, lock reacquired. (until c++14)
Comments
Post a Comment