Question

W.r.t ReadWriteLock, why would i need a lock while i am just trying to read something? Locking in my knowledge is to be used only if i am mutating a variable, not reading it to avoid concurrent threads trying to mutate the variable. So why we need a Lock for just reading?

Was it helpful?

Solution

The point of a ReaderWriterLock is to make sure that no other thread mutates something while you read it.

The read portion of the lock is not exclusive (there can be multiple concurrent readers), except with regard to the write portion (readers will wait for the writer and vice-versa).

OTHER TIPS

Some kinds of object encapsulate multiple aspects of mutable state which are expected to have some relationship to each other. For example, a List may have a Count property as well as a bunch of numbered slots. Suppose that a list starts out containing 100 items and a thread tries to enumerate them. Around the time that the enumerating thread reaches item 50, another thread tries to insert an item before number 25. What should happen?

If the enumerating thread acquires a read-lock token before it starts, and releases it when it's done, and the thread that wants to insert an item acquires a write-lock token first, the fact that the enumerating thread acquired a read-lock token will prevent the updating thread from modifying the list until the enumeration is complete. Note that one could have any number of enumerating threads operating simultaneously without any conflict, but all of them would have to complete (release their read-lock tokens) before any changes could be made to the list. Note that once a write-lock token request has been made, requests for read-lock tokens will be deferred until after the write-lock token has been issued and released; were this not done, a steady stream of read requests could prevent any write requests from ever getting issued.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top