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:

  1. out() thread tests isempty, finds true;
  2. in() thread sets isempty false , signals condition variable (but no-one wakes up, beacuse no-one waiting yet);
  3. out() thread calls cond.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

Popular posts from this blog

java - Spring Data JPA: Why findOne(id) executing delete query internally? -

python - Mongodb How to add addtional information when aggregating? -

java - Incorrect order of records in M-M relationship in hibernate -