0
4.0kviews
Readers and writer problem using Semaphore

Subject: Operating System

Topic: Synchronization and Deadlocks

Difficulty: High

1 Answer
1
311views

While defining the reader/writer’s problem, It is assumed that, many processes only read the file(readers) and many write to the file(writers).

File is shared among a many number of processes. The conditions that must be satisfied are as follows:

  1. Simultaneously reading of the file is allowed to many readers.
  2. Writing to the file is allowed to only one writer at any given point of time.
  3. Readers are not allowed to read the file while writer is writing to the file.

In this solution, the first reader accesses the file by performing a down operation on the semaphore file. Other readers only increment a counter, read count. When readers finish the reading counter is decremented.

When last one end by performing an up on the semaphore, permitting a blocked writer, if there is one, to write. suppose that while a reader is reading a file, another reader comes along. Since having two readers at the same time is not a trouble, the second readers and later readers can also be allowed if they come.

After this assumes that a writer wants to perform a write operation on the file. The writer can’t be allowed to write the file, since writer is suspended. The writer will suspend until no reader is reading the file. If new reader arrives continuously with short interval and perform reading, the writer will never obtain the access to the file.

To stop this circumstance, the program is written in a different way: when a reader comes and at the same time a writer is waiting, the reader is suspended instead of being allowed immediately.

Now writer will wait for readers that were reading and about to finish but does not have to wait for readers that came along with him. The drawback of this solution is that it achieves less concurrency and thus lower performance.

Writer process

while(TRUE)
 {
    wait(w)
    # perform write operation
    signal(w)
 }

Reader Process

 while(TRUE)
 {
   wait(m)
   read_count ++; //reader enters
   if (read_count == 1)
     wait(w) //blocks writer
     signal(m)
     # perform read operation
     wait(m)
     read_count --;
   if (read_count == 0) //No reader
     signal(w) //Writer can write 
     signal(m)
 }
Please log in to add an answer.