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
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 2always succeeds in locking the mutex so there is no synchronization taking place at all. In your simple case, the answer is also very simple: