1

This may sound basic for a question but I never had a formal (if there is) answer to it.

What is the best way (efficient way) to go about synchronizing the following:

  • Thread 1: while(1) read(shared_data)

  • Thread 2: while(1) lock(shared_mutex) write(shared_data) unlock(shared_mutex)

If what Thread 1 only does is read the data, does it need to lock the mutex too ? or just the write thread needs to do that ?

Thanx

1
  • What concrete type is shared_data? Commented Feb 6, 2012 at 23:17

3 Answers 3

2

Short Answer All threads that access shared data need to grab a lock that protects that data.

Long Answer If the reader does not lock the data to read it the thread can end up reading corrupted data if the writing thread is writing to the data while the reader is reading it. And in the modern multi-core/multiprocessor world don't count on any data type being atomically safe to read or write.

Edit (By Shahbaz): In fact, in your example, Thread 2 always succeeds in locking the mutex so there is no synchronization taking place at all. In your simple case, the answer is also very simple:

Thread 1: while(1) lock(shared_mutex) read(shared_data) unlock(shared_mutex) Thread 2: while(1) lock(shared_mutex) write(shared_data) unlock(shared_mutex) 
Sign up to request clarification or add additional context in comments.

Comments

0

If reading during the writing is not a problem then you don't need a lock for reading, but then you don't need a lock for writing. So you need to lock during reading here.

Comments

0

If you only have the 2 threads, then the mutex isn't doing anything useful. If it is OK for T2 to alter shared_data while T1 is reading it, then take the mutex out. If (and this is most likely) that ISN'T ok (since T1, upon a single read, can see some old and some new data), then T1 needs to protect the read with mutex calls.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.