The dining philosopher’s problem is useful for modeling processes that are competing for exclusive access-to a limited number of resources, such as I/O devices. Another famous problem is the readers and writers problem which models access to a database.

Imagine, for example, an airline reservation system, with many competing processes wishing to read and write it. It is acceptable to have multiple processes reading the database at the same time, but if one process is updating (writing) the database, no other processes may have access to the database, not even readers.

In this solution, the first reader to get access to the database does a down on the semaphore db. Subsequent readers merely increment a counter, rc. As readers leave, they decrement the counter, and the last one out.

Suppose that while a reader is using the database, another reader comes along. Since having two readers at the same time is not a problem, the second reader is admitted. Additional readers can also be admitted if they come along.

Now suppose that a writer shows up. The writer may not be admitted to the database, since writers must have exclusive access, so the writer is suspended.

Later, additional readers show up. As long as at least one reader is still active, subsequent readers are admitted. As a consequence of this strategy, as long as there is a steady supply of readers, they will all get in as soon as they arrive.

The writer will be kept suspended until no reader is present. If a new reader arrives, say, every 2 seconds, and each reader takes 5 seconds to do its work, the writer will never get in.

Solution to Readers Writers Problem using semaphore

typedef int semaphore;

semaphore mutex = 1;

semaphore write = 1;

int rc = 0;

void reader(void)

{     

      while (TRUE)

      {           

              down(mutex);

              r c = rc + 1;

              if (rc== 1)

              down(write);

              up(mutex);

              read_data_base();

              down(mutex);

              rc = rc - 1;

              if (rc = 0)

              up(write);

              up(mutex);

              use_data_read();

      }

}

void writer(void)

{

        while (TRUE)

        {

                think_up_data();

                down(write);

                write _data_base();

                up(write);

         }

}