Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to lock object when reading from it?

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?

like image 544
Andy Avatar asked Jan 31 '10 12:01

Andy


People also ask

Do we need mutex for reading?

Unless you use a mutex or another form of memory barrier. So if you want correct behavior, you don't need a mutex as such, and it's no problem if another thread writes to the variable while you're reading it.

Do you need to lock for read C#?

Reading does not require a lock; as long as you don't care about the 'correctness' of the read. It is only dangerous if you attempt to write without a lock.

Why do we need locks in Java?

Java lock acts as thread synchronization mechanisms that are similar to the synchronized blocks. After some time, a new locking mechanism was introduced. It is very flexible and provides more options in comparison to the Synchronized block.

What are read and write locks?

A ReadWriteLock maintains a pair of associated locks , one for read-only operations and one for writing. The read lock may be held simultaneously by multiple reader threads, so long as there are no writers. The write lock is exclusive.


1 Answers

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.

like image 58
Michał Bendowski Avatar answered Sep 28 '22 09:09

Michał Bendowski