0

While going through the Unreliable guide to locking, I found this line

Deadlocks are problematic, but not as bad as data corruption. Code which grabs a read lock, searches a list, fails to find what it wants, drops the read lock, grabs a write lock and inserts the object has a race condition.

My problem is I don't see how. My understanding is that you cannot acquire a write lock before all others have dropped a read lock. In this case, code would acquire a write lock only when there are no readers currently accessing that area.

  • What guarantees that no other thread will grab a write lock once you've dropped the read lock? – Mat Apr 06 '18 at 06:04
  • https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use – Mat Apr 06 '18 at 06:08
  • Before inserting if you're looking up the value again after taking the write lock then there is no problem. – amritanshu Apr 06 '18 at 07:14
  • @Mat, This is exactly what is confusing to me. My understanding of write_lock is this: while(test_and_set(0,lock_bit)!=1); where test_and_set is an atomic instr. The point is that the write lock is taken only if no other thread already has it and is not holding a read lock either, so I am not sure TOCTOU applies here. – abjoshi - Reinstate Monica Apr 06 '18 at 08:45
  • 2
    There is a "gap" between when you release the read lock and acquire the write lock. You don't know what (if anything) happened to the data in between. – Mat Apr 06 '18 at 08:58

0 Answers0