Do I need to lock object when reading from it?

Andy picture Andy · Jan 31, 2010 · Viewed 20.9k times · Source

I am writing a program where there is an object shared by multiple threads:

  • A) Multiple write threads write to the object (all running the same function)
  • B) A read thread which accesses the object every 5 seconds
  • C) A read thread which accesses the object there is a user request

It is obviously necessary to lock the object when writing to it, as we do not want multiple threads to write to the object at the same time.

My questions are:

  1. Is it also necessary to lock the object when reading from it?
  2. Am I correct to think that if we just lock the object when writing, a critical section is enough; but if we lock the object when reading or writing, a mutex is necessary?

I am asking this question because in Microsoft Office, it is not possible for two instances of Word to access a document in read/write access mode; but while the document is being opened in read/write mode, it is possible to open another instance of Word to access the document in read only mode. Would the same logic apply in threading?

Answer

Michał Bendowski picture Michał Bendowski · Jan 31, 2010

As Ofir already wrote - if you try to read data from an object that some other thread is modyfying - you could get data in some inconsistent state.

But - if you are sure the object is not being modified, you can of course read it from multiple threads. In general, the question you are asking is more or less the Readers-writers problem - see http://en.wikipedia.org/wiki/Readers-writers_problem

Lastly - a critical section is an abstract term and can be implemented using a mutex or a monitor. The syntax sugar for a critical section in java or C# (synchronized, lock) use a monitor under the covers.