Reputation: 1385
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
Upvotes: 7
Views: 5432
Reputation: 61
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.
Upvotes: 0
Reputation: 5818
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.
Upvotes: 1
Reputation: 1253
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.
Upvotes: 8
Reputation: 8928
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.
Upvotes: 8