Skip to content

Wrongs

Reader writers

alt text

  • there is NO deadlock, because lock ensure the writer and reader are mutually exclusive
  • step by step breakdown
  • when a writer is writing, it set writer = true. when there is an interruption, and the reader thread is executed, it will be trapped in the while loop and wait for the writer to finish, even when the reader is accidentlly awaked
  • therefore, no matter how many interruptions occur, no reader will be able to read the data until the writer is done.
  • then, the writer finished writing, and set writer = false, and boardcast the cv
  • now we have no writer, but suppose there is a new reader thread, it will acquire the lock and skip the while loop, and read the data without incrementing the readers variable
  • now, if there is a new writer thread, it will acquire the lock and check if writer || readers > 0, this is false, so it will start writing. in this case, we will have a writer and a reader at the same time, which is not allowed

Locks, wait, and notify

alt text

  • what happens if we did the following:

A race condition will occur, the lock is to guarantee that only one thread can change the count at a time, if count is changed outside the critcal section, then a race condition will occur because multiple threads can change the count at the same time, and the count will be inconsistent.

it is correct, notify the other thread while holding the lock, so that the other thread can wake up and acquire the lock, and then check the condition. if the condition is not met, it will wait again. this is a good way to avoid busy waiting.

a deadlock will occur,you must release the resource before going to sleep, otherwise the other thread cannot acquire the lock (resource) and will be blocked forever.