I read that a write lock is exclusive and a read lock is shared , so a piece of code which in readlock anyway can be accessed by multiple threads . What if no read lock is acquired by the threads in contention . Any way they are going to read only . Also what if a Thread acquiring a readlock tries to write something ?
Thanks
In the case of multithreaded code with both reads and writes, if a thread neglects to obtain a lock while reading, it risks reading inconsistent or garbage data due to a simultaneous write. For example, it could read a long variable just as that long variable was being written, and it could read the high half of the old value and the low half of the new value, which means the value it read would be complete garbage, something that was never actually written.
If a thread with a read lock writes without the write lock, it could cause other reading threads to read garbage data in a similar manner.
Duplicating @Solomon Slow comment here, as it helped me personally:
Read locks and write locks come in pairs: If thread R holds a read lock, it blocks thread W from obtaining the corresponding write lock, but it does not block thread S from getting the same read lock. A reader/writer lock pair allows any number of readers to "own" the read lock at the same time, OR it allows one writer to own the write lock, but it never allows a reader and a writer at the same time, and it never allows more than one writer at the same time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With