CS 537 Notes, Section #7: Semaphore Example: Readers and Writers.


Semaphore usage generally falls into two classes:

  1. Uniform resource usage, simple first-in-first-out scheduling: use semaphores for everything. This is usually the case. Use one semaphore for each constraint in the system.
  2. More complex patterns of resource usage: interaction between different users of a resource, or changing priorities: semaphores cannot capture the scheduling all by themselves. Must use state variables to record information about priorites, resource state. In this case, semaphores get used for two things:

    Whenever possible, cast problems into the first class. This usually can be done.

    Unfortunately, sometimes a resource is shared by different classes of users; that is, they use the resource in different ways. Potentially the different kinds of usage interact. For example, consider a shared database with readers and writers. It is safe for any number of readers to access the database simultaneously, but each writer must have exclusive access. Example: checking account (statement-generators are readers, tellers are writers).

    Reader Process: Writer Process:
    
    StartRead ()
    {
         Lock.P();
         if ((AW+WW) == 0) {
             OKToRead.V();
             AR++;
         } else  {
             WR++;
         }
         Lock.V();
         OKToRead.P();
    }
    
    
    StartWrite ()
    {
         Lock.P();
         if ((AW+AR+WW) == 0) {
             OKToWrite.V();
             AW++;
         } else  {
             WW++;
         }
         Lock.V();
         OKToWrite.P();
    }
    
    
    EndRead ()
    {
         Lock.P();
         AR--;
         if ((AR == 0) and (WW > 0)) {
             OKToWrite.V();
             AW++;
             WW--;
         }
         Lock.V();
    }
    
    
    EndWrite ()
         Lock.P();
         AW--;
         if (WW>0) {
             OKToWrite.V();
             AW++;
             WW--;
         } else {
             while (WR>0) {
                 OKToRead.V();
                 AR++;
                 WR--;
             }
         }
         Lock.V();
    }
    
    
    main ();
    {
        StartRead();
        // --read the necessary data--
        EndRead();
    }
    
    
    main ();
    {
        StartWrite();
        // --write the necessary data--
        EndWrite();
    }
    

    Examples:


    Reader/Writers

    Questions:



    Copyright © 1997, 2002, 2008 Barton P. Miller
    Non-University of Wisconsin students and teachers are welcome to print these notes their personal use. Further reproduction requires permission of the author.