5

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

jayendra bhatt
  • 1,337
  • 2
  • 19
  • 41

4 Answers4

8

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.

Warren Dew
  • 8,790
  • 3
  • 30
  • 44
  • That implies the read lock is atomic . And you mean there is no obstruction for the read lock acquired thread to do a write operation ? correct me if am wrong – jayendra bhatt Oct 28 '15 at 07:24
  • 1
    @jayendrabhatt It's very hard to understand your questions. What do you think it means for a lock to be atomic? – David Schwartz Oct 28 '15 at 07:28
  • 4
    @jayendrabhatt, 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. – Solomon Slow Oct 28 '15 at 12:51
7

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.

gokareless
  • 1,165
  • 1
  • 10
  • 26
1

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.

dz902
  • 4,782
  • 38
  • 41
0

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.

Echo Zeng
  • 61
  • 4