Search code examples
.netreaderwriterlock

How is a ReaderWriterLock shared amongst threads? Is it implemented with a singleton?


When you want to use a ReaderWriterLock you declare it like this:

ReaderWriterLock rwLock = new ReaderWriterLock;

Well if you are doing that for all your different threads that are going to access some resource that you want to protect, they (presumably) are all using differnt ReaderWriterLock instances.

How is the ReaderWriterLock instance shared amongs threads?

Also, as a bonus, can someone confirm for me that what you are really "locking" is the ReaderWriterLock state, not any resource. Unlike lock(someResourceToLock), you aren't locking anything but the ReaderWriterLock instance's state (whether it is in read or write mode, and whether you are allowed to read and write yet).


Solution

  • If you are using the ReaderWriterLock rwLock = new ReaderWriterLock per thread or per method (i.e. as a method variable), then your code is most-likely broken. It is not a singleton; it relies on all threads accessing the protected data using the same lock. This is most commonly achieved by placing the lock in a field, i.e.

    class Foo {
        ReaderWriterLock rwLock = new ReaderWriterLock();
        // lots of code accessing the rwLock field for this instance
    }
    

    Also - maybe consider ReaderWriterLockSlim in many scenarios; less overhead. Re your follow-up; when acquiring the lock you are changing the internal state (in a thread-safe manner) to preserve the "many-readers nand single-writer" expectation (perhaps blocking until that is possible, i.e. conflicting locks have been withdrawn).