Tackling the reader-writer problem with Semaphores

Any one who has come across Process Synchronization must have read about the famous reader-writer problem. Let me put the problem in an easier way.  Consider Adu, Shankie and Somu wants to edit on the same shared file. All are connected to the same file somehow and needs access to it. Say all three of them wants to read it. There is no harm for all of them to read it at the same time. Now, imagine a situation when Shankie wants to write into the file and others want  to read. It is not correct for Somu and Adu to read a file while Shankie is editing it. He may be erasing some lines and might be adding more. Either Adu and Somu must read first and then allow Shankie to write or vice versa. Problem becomes terrible when Somu also decides to write. Somu edited half the file and she saved and left. At the same time Shankie had opened it before and he saves after Somu saves. All the changes made by Somu will be gone when Shankie saves the file.

This is a classic Synchronization problem associated with multi-programming or multi-threading. Here is the statement :

Many threads must access the same shared memory at one time, some reading and some writing, with the constraint that no process may access the share for reading
or writing while another process is in the act of writing to it.

Here is an implementation of the reader-writer problem using semaphores in linux.

if(readcount ==1)
//Do the reading
if(readcount == 0)

You can check out the following link  for the whole code.



One thought on “Tackling the reader-writer problem with Semaphores

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s