Lecture 14

Review -- basic uses of semaphores

   mutual exclusion
   signaling
   split binary semaphores -- combines exclusion and signaling
   resource counting (general semaphores)


The Dining Philosophers -- Section 4.3

   define the problem:  philosophers, table, forks, plates

   solution idea:  pick up two forks

      sem forks[1:5] = ([5] 1);   # each fork is a critical section
                                  # so use 1 for initial value

      first attempt for philosopher code

         P(fork[i]); P(fork[i%5 + 1]);
         "eat"
         V(fork[i]); V(fork[i%5 + 1]);
         "think"

      what is the problem?  deadlock (deadly embrace) due to circular waiting

      solutions:

         (a) change order for some, but not all

         (b) limit number at table:

               sem limit = 4;
               P(limit); above code; V(limit);
       
               works, but uses an extra semaphore


The Readers/Writers Problem -- Section 4.4

   another classic problem; VERY common
   
   define the problem and give code outlines

   (a) develop overconstrained solution:

           sem rw = 1;

           P(rw);           P(rw);
           read             write;
           V(rw);           V(rw);

        avoids simultaneous access, but precludes concurrent reads
        

   (b) let's relax the solution just enough to allow concurrent reads

       idea:  first reader to arrive does P(rw) and last to leave does V(rw)
              this requires keeping a counter

            nr++
            if (nr == 1) P(rw);
            "read"
            nr--
            if (nr == 0) V(rw);

        but now nr is a shared variable that has to be accessed atomically;
        we know how to provide that:  use a critical section!  so we get:

            P(mutexR);
              nr++
              if (nr == 1) P(rw);
            V(mutexR);
            "read"
            P(mutexR);
              nr--
              if (nr == 0) V(rw);
            V(mutexR);


            P(rw);
            "write"
            V(rw);


   (c) properties of solution (b)

        guarantees appropriate exclusion, but it is not fair.  why?

        it gives readers preference

        how can we make the solution fair?  or give writers preference?
        very tricky to modify the above to do this.

        next way we'll see a different way to solve the problem
        that is quite easy to modify to change scheduling