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.

writer()
{
wait(wrt);
signal(wrt);
}
reader()
{
wait(mutex);
readcount++;
if(readcount ==1)
wait(wrt);
signal(mutex);
//Do the reading
wait(mutex);
readcount--;
if(readcount == 0)
signal(wrt);
signal(mutex);
}

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

https://github.com/sreepriya/Process-Synchronisation/blob/master/reader_writer.c

Advertisements