-2

enter image description here

Above is reader write problem solution where writer has preference over reader.

Suppose, initially 1000 readers start executing code to read data (suppose reading data code is huge and takes 1 sec for each thread) then 1 writer tries to write data. So the writer has to wait for 1000 readers to finish first (i.e., 1000 sec).

For example, in an application where 1 writer updates time and many readers read time, the writer has to wait for 1000 seconds, which is huge.

Is there any solution in which, when a writer tries to write, all readers will be preempted until the writer completes its task?

Jay Sullivan
  • 17,332
  • 11
  • 62
  • 86
Suri
  • 3,287
  • 9
  • 45
  • 75
  • 1
    Wow! This post really needs to be reformatted. I can't make sense of it to do it however. Please take a minute and remove the indenting on non-code text. – Gray Jun 15 '12 at 18:41
  • I have formatted the questions – Suri Jun 15 '12 at 18:44

2 Answers2

0

What precisely does "preempt" mean? You can't just take them off the CPU because that does not solve the problem. The readers expect the state they are reading to be stable. If you "suspend" the readers, take the write lock, modify the state, release the lock and resume the readers, they will see changed state and malfunction.

The purpose of the read lock is to ensure the data does not change while the readers execute. if you remove that property this locking strategy makes no sense anymore.

usr
  • 168,620
  • 35
  • 240
  • 369
  • whatever you explain is correct and this is my doubt. if all reader are executing then writer comes and has to write (should not be any wait for him)whats need to done? because if writer waits for 1 reader its ok but if read for 10000 readers then obviously it will be delay for writer. – Suri Jun 18 '12 at 04:58
0

Since the number of readers are way more than writers, you might end up starving the writers thread. One simple policy you can introduce is, if a writer is waiting to write, you can stop granting any more read locks to upcoming read requests. This will, at least ensure that writer will not starve. The delay for writer depends on the actual use case.

  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 10 '22 at 02:41