'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



Solution 1:[1]

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.

Solution 2:[2]

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.

Solution 3:[3]

This is interesting as the name "readlock" or "reader-lock" is probably a bit misleading.

I found it easier to think it as a mode switch, you switch to read-only mode, or write-only mode. You switch mode by acquiring corresponding locks.

Solution 4:[4]

Like if you want a row in this table, and you do not want any cell would be changed during the period, so you can add one read-lock.

Other guys can also read, it doesn't matter.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gokareless
Solution 2 Warren Dew
Solution 3 dz902
Solution 4 Echo Zeng