c - What if a condition variable signals to a locked thread? -
in (pseudo-)code below, cond might wake while shouldn't, whatever reason. put while loop there. when wake up, still consume lock, guaranteed in out() 1 thread doing job.
but happens if, while there spurious wake-up in out(), @ same time in() signals out(), @ moment out() locked because of spurious wake-up. happens if cond signals locked thread?
in() inlock.lock() isempty = false cond.signal() inlock.unlock() out() outlock.lock() while isempty cond.wait(outlock) isempty = true outlock.unlock()
note
well, 100% safe, know can use single mutex both in() , out(), data structure i'm using 100% safe when input , output happens @ same time; type of queue. , think performance compromise block reading out queue while filling in new data or vice versa.
i did consider using semaphores, problems many c , c++ libraries don't implement semaphores whatever reason.
you have use same mutex when in() thread sets isempty = false , out() thread tests while (isempty). otherwise, can happen:
out()thread testsisempty, finds true;in()thread setsisemptyfalse , signals condition variable (but no-one wakes up, beacuse no-one waiting yet);out()thread callscond.wait(), blocks forever, despite fact queue not empty anymore.
note in sequence there hasn't been spurious wakeup - it's plain old race condition.
as long update isempty same mutex held when test isempty, interleaving can't happen.
Comments
Post a Comment