Readerwriterlock vs two lock ? RRS feed

  • Question

  • What is difference between readerwriterlock and two lock ?

    I can create

    private object _readLock = new obect();

    private object _writeLock = new obect();

    void Read(){





    void Write(){





    Or as analog for readerwriterlockslim I can do the same with

    private SpinLock _readLock = ...

    private SpinLock _writeLock =

    Media Store

    Thursday, May 3, 2018 9:58 AM


  • The purpose of a reader/writer lock is to effectively allow any # of reads with synchronized writes. Can you do it yourself? Yes. Would you? Probably not. There is no benefit in reinventing the wheel and you are highly unlikely to do it right or efficiently compared to the version that has been built in and has been working/optimized for years.

    In your first example (which isn't a reader/writer lock BTW) you are taking a lock each time you read. That means only 1 person can read at a time. Your performance is going to tank. A reader/writer lock would allow any # of readers. Only the write has a lock and it is written such that it waits for the readers to finish before it can write. Your version doesn't do any of that. In fact your reader/writer lock isn't really doing anything other than serializing reads and writes. In your implementation a writer could be writing over the very data being read so you aren't really doing any locking at all other than prevent more than one read or write at a time.

    Michael Taylor

    • Marked as answer by SmartWhy Friday, May 11, 2018 9:38 AM
    Thursday, May 3, 2018 2:04 PM