Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference of upgradeable read lock vs a write lock in C# ReaderWriteLock

Whats the difference between an upgradeable read lock and a write lock in the ReaderWriterLock class?

Based on the MSDN description, only one thread can enter an upgradeable read lock. If I follow correctly, I could just forget about upgrading it since its the same as a write lock. Anything I'm missing?

like image 235
Mel Avatar asked May 22 '12 05:05

Mel


2 Answers

(I'm assuming you mean ReaderWriterLockSlim, as I don't think ReaderWriterLock has an upgradeable read mode.)

Although only one thread can enter an upgradeable read lock, one thread can have an upgradeable read lock and other threads can still enter a read lock:

Only one thread can enter upgradeable mode at any given time. If a thread is in upgradeable mode, and there are no threads waiting to enter write mode, any number of other threads can enter read mode, even if there are threads waiting to enter upgradeable mode.

Compare that with a write lock:

When there are threads waiting to enter write mode, additional threads that try to enter read mode or upgradeable mode block until all the threads waiting to enter write mode have either timed out or entered write mode and then exited from it.

In other words, a write lock is entirely exclusive, whereas an upgradeable read lock will allow other threads to keep entering/exiting for read mode until the upgrade is needed.

like image 199
Jon Skeet Avatar answered Oct 12 '22 22:10

Jon Skeet


I think that UpgradableReadLock is a special ReadLock that can be turned into a WriteLock. What MSDN states is that only one thread can turn into WriteLock at the time. This is logical as there can be only one writer.

like image 44
dzendras Avatar answered Oct 12 '22 23:10

dzendras