Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why to use a readlock?

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

like image 694
jayendra bhatt Avatar asked Dec 15 '22 11:12

jayendra bhatt


2 Answers

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.

like image 85
Warren Dew Avatar answered Dec 17 '22 00:12

Warren Dew


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.

like image 27
gokareless Avatar answered Dec 17 '22 01:12

gokareless