This is a theoretical question; I don't have an actual issue to solve, I just want to understand the reasoning behind the way this works.
I found out that if a thread omits to exit a ReaderWriterLock then other threads will fail to acquire a lock even after the original thread terminates. Is there a good reason why ReaderWriterLock does not grant the lock to waiting threads as soon as the thread that owns the lock terminates?
Here is a test case that demonstrate the issue.
static void Main(string args)
ReaderWriterLockSlim readerWriterLock = new ReaderWriterLockSlim();
Thread t1 = new Thread((a) =>
// this thread omits to Exit the lock....
Thread t2 = new Thread((a) =>
// wait for all threads to finish
The simple answer: There is no easy way for the writer thread to know that the reader threads have terminated, without also making the locking operations expensive.
Locks are usually implemented as values in memory, so acquiring an releasing the lock involve changing these values. If a thread sets the value to acquire the lock, then crashes, the only way another lock can be acquired is if you have some background thread that polls for dead threads, looks at their list of recently acquired locks, and cleans them up.
In addition to this being expensive and needing a lot of plumbing, it is potentially unsafe because you don't know exactly how far the thread got before it crashed.
It probably wouldn't be too hard for a lock to store the identity of the thread that holds it exclusively, or a list of threads that hold it non-exclusively. The locking code could then check periodically while it's blocked to see if any or all of the threads that are blocking it are still alive. The biggest problem with doing this is that there's no standard way for threads to indicate at what moments the entities being protected by the lock are in a legitimate state or an invalid one. If a thread which is holding a lock dies while the protected entities are in an invalid state, access to those entities should remain forbidden unless or until some code which is knows how to deal with the corruption has done so.