Tech Off Thread

3 posts

Forum Read Only

This forum has been made read only by the site admins. No new threads or comments can be added.

ReaderLock vs WritterLock, use which when, where and why?

Back to Forum: Tech Off
  • User profile image
    phreaks

    I am trying to hone my multi-threading skills and understanding.
    One thing I am having a terrible time trying to comprehend is how to know when, where and why to use a Readerlock vs a Writterlock.

    How do I know when to use ReaderLock or when to use WritterLock?

    Does it matter?
    Do I even *really* need to apply locking all the time, or just specific scenarios.

    Perplexed

  • User profile image
    Minh

    If your app only "read" from an object, even from multiple threads, it's perfectly safe. You won't even need to lock anything.

    Now, as soon as it's possible to "write" (I guess a better term is make a change to a member variable) to your object from multiple thread, you're going to need some sort of locking mechanism so that 2 threads aren't trying to change the same variable.

    So, it's easy to see why you'd need to acquire a write lock -- to prevent another thread from running the same section of code (trying to write something). The thread execution will pause at the acquire until the other thread release the writer lock, then execution resume.

    Reader locks lets multiple threads read the same data -- if the only thing they're doing are reads.

    Reader locks also work with writer locks... if there are already some reader locks, a writer lock will wait until all previous reader locks have been released -- so that a thread wouldn't change a piece of data somebody else is looking at.

    Also, a reader lock will wait if there's a writer lock in progress -- so that a thread wouldn't read a piece of data somebody else is changing.

  • User profile image
    phreaks

    Ah!
    Thank-you, that is the best explanation I have seen yet.

Conversation locked

This conversation has been locked by the site admins. No new comments can be made.