6pp - CP2002 Quick Review Quick Review Binary Semaphore Binary

Document Sample
6pp - CP2002 Quick Review Quick Review Binary Semaphore Binary Powered By Docstoc
					                                                                                                                Quick Review
                                                                                                  We have moved from issues relating to CPU scheduling
                                                                                                  onto process synchronisation;
                         CP2002
                                                                                                  Last week, we introduced ideas of entry section, critical
                  Operating Systems                                                               section, exit section, and remainder section;
                                                                                                  The critical section problem considered mutual
                                                                                                  exclusion (there can be only one), progress (interested
                JCU School of Information Technology
                                                                                                  processes participate in the selection of a winner, and
                                                                                                  selection may not be delayed forever), and bounded
                                                                                                  waiting (a constraint on fairness);
                                                                                                  A number of algorithms were considered including the
                                                                                                  bakery algorithm;



                                                                            CP2002 – p.1/102                                                     CP2002       Quick Review – p.2/102




                 Quick Review                                                                               Binary Semaphore
  The idea of wait-loops was reviewed and in the case of                                          A semaphore that is initialised to 1 and used by two or
  relatively long critical sections, it was noted that it made                                    more processes to ensure that only one of them can
  more sense for the process waiting for access to                                                enter its critical region at the same time is called a
  suspend itself even though that incurred the overheads                                          binary semaphore.
  of a context switch. When the critical section was short,                                     ◦ As critical section access is mutually exclusive, the
  it seemed reasonable to keep wait-looping and avoid                                             semaphore may also be called a mutex.
  the process state change overheads — this was made
  even more respectable by naming it a spin-lock;                                               ◦ A binary semaphore can be obtained from a counting
                                                                                                  semaphore by allowing the binary semaphore to be
  We noted that synchronisation is a more difficult                                                able to count between 0 and 1 (i.e. a 1 bit counter).
  problem with multi-processor systems;
                                                                                                ◦ A binary semaphore may be easier to implement given
  We now complete synchronisation by considering some                                             some computer architectures.
  classic problems and the issues relating to atomic
  transactions.

                                                          CP2002       Quick Review – p.3/102                                                 CP2002      Binary Semaphore – p.4/102




             Binary Semaphore                                                                               Binary Semaphore
  If an architecture better suits a binary semaphore, how                                         wait()
  can a counting semaphore be implemented?                                                        {
                                                                                                      wait(S1);
◦ Recall that a counting semaphore consist of
                                                                                                      C--;
  uninterruptible code fragments:
                                                                                                      if (C < 0){
  wait(S){ while( S<=0 ){}; S--; }
                                                                                                        signal(S1);
  signal(S){ S++; }
                                                                                                        wait(S2);
◦ Given the data structure                                                                            }
  binary-semaphore S1, S2;                                                                            signal(S1);
  int C;                                                                                          }
  with initial values S1=1, S2=0 and C set to the initial
  value of counting semaphore S, the following code
  implements a wait and signal on S:


                                                       CP2002      Binary Semaphore – p.5/102                                                 CP2002      Binary Semaphore – p.6/102
             Binary Semaphore                                                                                            Classic Synchronisation Problems [7.5]
  signal()                                                                                                                   The classic synchronisation problems are used to test
  {                                                                                                                          new synchronisation schemes.
      wait(S1);
                                                                                                                             Counting semaphores are used in the following code
      C++;
                                                                                                                             samples.
      if (C <= 0)
        signal(S2);
      else
        signal(S1);
  }
◦ Observe in signal() that S2 is non-zero whenever S
  would cause blocking (i.e. S<=0).




                                                                       CP2002             Binary Semaphore – p.7/102                                                               CP2002         Classic Synchronisation Problems [7.5] – p.8/102




 Bounded-Buffer Problem [7.5.1]                                                                                             Bounded-Buffer Problem [7.5.1]
  The Bounded-Buffer Problem for n buffers is now                                                                          ◦ Producer process:
  implemented with wait() and signal().                                                                                      do
◦ The shared semaphores are semaphore full,                                                                                    ...
  semaphore empty, and semaphore mutex.                                                                                        produce an item in nextp
◦ Semaphores full and empty count the number of full                                                                           ...
  and empty buffers respectively, and semaphore mutex                                                                          wait(empty);
  makes buffer accesses mutually exclusive.                                                                                    wait(mutex);
                                                                                                                               ...
◦ Initial values: full=0, empty=n, mutex=1.                                                                                    add nextp to buffer
                                                                                                                               ...
                                                                                                                               signal(mutex);
                                                                                                                               signal(full);
                                                                                                                              while (1);


                          CP2002    Classic Synchronisation Problems [7.5]    Bounded-Buffer Problem [7.5.1] – p.9/102                                CP2002   Classic Synchronisation Problems [7.5]   Bounded-Buffer Problem [7.5.1] – p.10/102




 Bounded-Buffer Problem [7.5.1]                                                                                             Bounded-Buffer Problem [7.5.1]
  Consumer process:                                                                                                        ◦ Semaphore mutex is used as a “wrapper” around
  do                                                                                                                         manipulation of buffer contents.
    wait(full)                                                                                                             ◦ The code symmetry is interesting, as the producer and
    wait(mutex);                                                                                                             consumer have their semaphores empty and full
    ...                                                                                                                      exchanged. An interpretation of this is that the producer
    remove an item from buffer to nextc                                                                                      makes full buffers and the consumer makes empty
    ...                                                                                                                      buffers.
    signal(mutex);
    signal(empty);
    ...
    consume the item in nextc
    ...
   while (1);


                          CP2002   Classic Synchronisation Problems [7.5]    Bounded-Buffer Problem [7.5.1] – p.11/102                                CP2002   Classic Synchronisation Problems [7.5]   Bounded-Buffer Problem [7.5.1] – p.12/102
 Readers-Writers Problem [7.5.2]                                                                                           Readers-Writers Problem [7.5.2]
  This problem concerns the sharing of a data object                                                                        One solution is to have any new writer wait until there
  between multiple processes of two types: reading or                                                                       are no readers with access, and to allow any new
  writing.                                                                                                                  reader to join in if an existing process is already
◦ It is safe for two or more readers to access data.                                                                        reading.
◦ However, when a writer is to have access, there can be                                                                  ◦ This is called the first readers-writers problem.
  no other processes with access (even a reader would                                                                     ◦ This solution can cause a write process to be starved of
  have problems if data was temporarily inconsistent due                                                                    access.
  to a writer modifying it).                                                                                                Another solution is to have any new readers wait if there
◦ More than two variations of the solution exist,                                                                           exists a process wishing to write.
  depending on the priority chosen between reader and                                                                     ◦ This is called the second readers-writers problem.
  writer.
                                                                                                                          ◦ This solution can cause a read process to be starved of
                                                                                                                            access.

                           CP2002   Classic Synchronisation Problems [7.5]   Readers-Writers Problem [7.5.2] – p.13/102                               CP2002   Classic Synchronisation Problems [7.5]   Readers-Writers Problem [7.5.2] – p.14/102




 Readers-Writers Problem [7.5.2]                                                                                           Readers-Writers Problem [7.5.2]
  Solution for the first readers-writers problem:                                                                            Writer process:
◦ The shared semaphores are semaphore mutex and                                                                             wait(wrt);
  semaphore wrt, and readers are counted with int                                                                           ...
  readcount.                                                                                                                writing is performed
◦ Initial values: mutex=wrt=1, readcount=0.                                                                                 ...
                                                                                                                            signal(wrt);
                                                                                                                          ◦ The writer action is mutually exclusive by virtue of the
                                                                                                                            wrt mutex.




                           CP2002   Classic Synchronisation Problems [7.5]   Readers-Writers Problem [7.5.2] – p.15/102                               CP2002   Classic Synchronisation Problems [7.5]   Readers-Writers Problem [7.5.2] – p.16/102




 Readers-Writers Problem [7.5.2]                                                                                           Readers-Writers Problem [7.5.2]
  Reader process:                                                                                                         ◦ The reader processes perform tests and updates to the
                                                                                                                            count of the number of readers, integer readcount,
  wait(mutex);                                                                                                              safely by virtue of the mutex named ... mutex.
  readcount++;
  if (readcount == 1)                                                                                                     ◦ Should a reader be the first to try to read, notice that
    wait(wrt);                                                                                                              after performing a wait(mutex) and incrementing
  signal(mutex);                                                                                                            readcount, it will (as would be reader number 1) test
  ...                                                                                                                       true for (readcount==1) and so perform a
  reading is performed                                                                                                      wait(wrt) — if any writer is active, this will perform a
  ...                                                                                                                       wait on wrt and any other would-be readers will get
  wait(mutex);                                                                                                              temporarily caught on wait(mutex) while the first
  readcount--;                                                                                                              would-be reader waits on wait(wrt).
  if (readcount == 0)                                                                                                       When a writer ceases to write and executes
    signal(wrt);                                                                                                            signal(wrt), it is the process scheduler which
  signal(mutex):                                                                                                            determines which of any pending would-be readers or
                                                                                                                            would-be writers gain access.
                           CP2002   Classic Synchronisation Problems [7.5]   Readers-Writers Problem [7.5.2] – p.17/102                               CP2002   Classic Synchronisation Problems [7.5]   Readers-Writers Problem [7.5.2] – p.18/102
Dining-Philosophers Problem [7.5.3]                                                                                             Dining-Philosophers Problem [7.5.3]
   This problem is an example of a large class of                                                                                ◦ Any would-be diner who has picked up the chopstick on
   concurrency-control problems. It also brings new                                                                                the left and the chopstick on the right becomes an
   meaning to the concept of a process starving.                                                                                   actual diner i.e. eats without releasing the chopsticks,
                                                                                                                                   until replete.
 ◦ In the problem instantiation involving dining
   philosophers, one has 5 philosophers seated at a round                                                                          Philosopher lifestyle algorithm:
   table with a single chopstick between each would-be                                                                           ◦ The shared semaphores are semaphore
   diner. It is assumed that a philosopher is either eating                                                                        chopstick[5].
   or philosophising.                                                                                                            ◦ Initial values: chopstick[]={1,1,1,1,1}.
 ◦ A philosopher may pick up only one unused chopstick                                                                           ◦ A simple solution is suggested where chopsticks are
   (located on either side of their place at the table) at a                                                                       represented by the semaphores chopstick[], and where
   time. As philosophers are well mannered, they do not                                                                            wait(chopstick[j]) corresponds to waiting until
   snatch chopsticks from someone else.                                                                                            access is gained to chopstick[j] and
                                                                                                                                   signal(chopstick[j]) corresponds to finishing with
                                                                                                                                   chopstick[j].
                             CP2002   Classic Synchronisation Problems [7.5]   Dining-Philosophers Problem [7.5.3] – p.19/102                              CP2002   Classic Synchronisation Problems [7.5]   Dining-Philosophers Problem [7.5.3] – p.20/102




Dining-Philosophers Problem [7.5.3]                                                                                             Dining-Philosophers Problem [7.5.3]
   Philosopher i lifestyle                                                                                                       ◦ While this looks feasible, it is easy to put forward
   do                                                                                                                              counter examples that break this algorithm e.g. if all
     wait(chopstick[i])                                                                                                            would-be diners take the chopstick on their left, they
     wait(chopstick[(i+1) % 5])                                                                                                    proceed to deadlock (and starve) forever.
     ...                                                                                                                         ◦ Deadlock work-arounds exist e.g. create a critical
     eat until replete                                                                                                             region involving acquisition of two chopsticks, or have
     ...                                                                                                                           rules for odd and even philosophers, etc. However,
     signal(chopstick[i]);                                                                                                         these work-arounds do not guard against long term loss
     signal(chopstick[(i+1) % 5]);                                                                                                 of access (and subsequent starvation).
     ...                                                                                                                         ◦ A better solution is presented later, using monitors.
     philosophise
     ...
    while (1);


                             CP2002   Classic Synchronisation Problems [7.5]   Dining-Philosophers Problem [7.5.3] – p.21/102                              CP2002   Classic Synchronisation Problems [7.5]   Dining-Philosophers Problem [7.5.3] – p.22/102




       Higher Level Mechanisms                                                                                                  [Conditional] Critical Regions [7.6]
   It is relatively easy to make programming mistakes with                                                                         The critical regions form of synchronisation solution is
   the use of the fundamental tools such as wait(),                                                                                based on the use of a shared variable that can be
   signal(), etc.                                                                                                                  accessed by a statement S when a condition B is true.
 ◦ A better solution might be to offer the programmer                                                                            ◦ The suggested syntax to represent this in
   some simple-to-use synchronisation mechanism via a                                                                              Silberschatz-et-al for a variable v is
   clean interface. In fact, there might be a suite of such                                                                        region v when (B) S;
   mechanisms in the support libraries/classes of typical                                                                        ◦ Regions referring to the same shared variable exclude
   modern high level languages.                                                                                                    each other in time.
 ◦ Another approach to a solution is to program the                                                                              ◦ When a process tries to execute the region statement,
   skeleton of each type of solution and have the                                                                                  the Boolean expression B is evaluated. If B is true,
   programmer adapt (or extend) it to their needs. The                                                                             statement S is executed (with sole access). If B is false,
   programmer will need to provide functions which                                                                                 the process is delayed B becomes true and no other
   provide the tests needed to determine critical region                                                                           process is in the region associated with v.
   access etc.
                                                                          CP2002         Higher Level Mechanisms – p.23/102                                         CP2002        Higher Level Mechanisms      [Conditional] Critical Regions [7.6] – p.24/102
[Conditional] Critical Regions [7.6]                                                                                  [Conditional] Critical Regions [7.6]
  To apply this idea to the bounded-buffer problem, we                                                                  Producer code:
  can make the buffer, indices, and counters be                                                                         region v when( v.count < n) {
  encapsulated in a shared, single access variable v i.e.                                                                 buffer[v.in] = nextp;
  struct v_type {                                                                                                         v.in = (v.in+1) % n;
    int buffer[n];                                                                                                        v.count++;
    int count, in, out;                                                                                                 }
  };                                                                                                                    Consumer code:
  v_type v;
                                                                                                                        region v when (v.count > 0) {
                                                                                                                          nextc = buffer[v.out];
                                                                                                                          v.out = (v.out+1) % n;
                                                                                                                          v.count--;
                                                                                                                        }


                                 CP2002   Higher Level Mechanisms   [Conditional] Critical Regions [7.6] – p.25/102                                  CP2002   Higher Level Mechanisms   [Conditional] Critical Regions [7.6] – p.26/102




[Conditional] Critical Regions [7.6]                                                                                  [Conditional] Critical Regions [7.6]
  An implementation of the region v language                                                                          ◦ Whenever any process completes execution of its S,
  construct involves some additional (private) variables,                                                               any pending processes in the wait queues have their
  associated with each struct v. Of most importance are                                                                 entry conditions B re-evaluated — one can resume and
  3 semaphores:                                                                                                         execute its S if its B is now true.
  semaphore mutex, first-delay,
  second-delay;                                                                                                       ◦ In order to minimise the re-evaluation work, techniques
                                                                                                                        such as compiler data flow analysis can identify code
◦ When the region statement is executed, the condition                                                                  fragments that output results used as input to any
  B is first evaluated. If B is true, statement S is                                                                     particular B so that a minimum set of B are checked.
  immediately executed (with single access to V
  guaranteed).                                                                                                        ◦ Comment by PM: the dual stage wait queue is thought
                                                                                                                        to be required in order to cleanly handle updates of the
◦ If B is false, the process enters a FIFO wait queue on                                                                B functions that can come from changes due to the
  first-delay and eventually passes onto a FIFO wait                                                                    current process (timing is related to this process) and
  queue on second-delay. The wait queue is provided                                                                     changes due to other processes (timing is unrelated to
  with a copy of the entry test B for later re-evaluation to                                                            this process).
  determine entry.
                                 CP2002   Higher Level Mechanisms   [Conditional] Critical Regions [7.6] – p.27/102                                  CP2002   Higher Level Mechanisms   [Conditional] Critical Regions [7.6] – p.28/102




                 Monitors [7.7]                                                                                                       Monitors [7.7]
  A Monitor is another high level synchronisation                                                                     ◦ In order to make the monitor useful to us, we must
  construct that is characterised by a set of programmer                                                                provide some member functions that relate to our
  defined operations.                                                                                                    application. One aspect of this is to define some test or
  Note: this explanation initially differs in approach to that                                                          condition functions that relate to the problem. This may
  of Silberschatz. Here, we aim to build on your                                                                        involve defining a condition construct such that an
  knowledge of a class from C++ to improve clarity.                                                                     instantiation condition x provides member functions
                                                                                                                        x.wait() and x.signal().
◦ The basic monitor is defined with a set of private data
  variables that are shared amongst the member                                                                        ◦ As we have seen elsewhere, multiple .wait() and
  functions of the monitor class e.g. the semaphores and                                                                .signal() calls are handled in a queue. While the
  queue length counters described in section ??.                                                                        pending wait/signal conditions could be handled in a
                                                                                                                        FIFO queue structure, we could have an alternative
◦ There is a constructor to initialise all semaphores as                                                                mechanism that also considered some pre-assigned
  appropriate.                                                                                                          priorities, wait times (aging), etc.


                                              CP2002        Higher Level Mechanisms      Monitors [7.7] – p.29/102                                                CP2002        Higher Level Mechanisms      Monitors [7.7] – p.30/102
               Monitors [7.7]                                                                                       Monitors [7.7]
  An interesting issue arises if two or more monitors are                                             Dining-Philosopher problem take 2:
  to share the same condition. Suppose a process Q is                                               ◦ This solution is dead-lock free.
  currently suspended waiting on some condition x, and
  that a process P has invoked x.signal() — should P                                                ◦ The philosophers are now said to be in 1 of 3 states:
  wait so that Q can leave the monitor and resume                                                     philosophising, hungry, eating. A shared state variable
  execution (option 1), or should P keep executing and let                                            is defined as:
  Q take its chances later (option 2)?                                                                enum { philosophising, hungry, eating }
                                                                                                      state[5];
◦ Both approaches have been used, with Hoare originally                                               with all initial states set to philosophising.
  analysing option 1 and a (non-standard) variant of C
  called Concurrent C choosing option 2.                                                            ◦ A philosopher i can set variable state[i] to eating if and
                                                                                                      only if
                                                                                                      (state[i-1]!=eating)&&(state[i+1]!=eating).
                                                                                                    ◦ We also need condition self[5]; to queue up
                                                                                                      philosophers who want to eat but cannot access the
                                                                                                      tools to do so.
                                     CP2002   Higher Level Mechanisms   Monitors [7.7] – p.31/102                                          CP2002   Higher Level Mechanisms   Monitors [7.7] – p.32/102




               Monitors [7.7]                                                                                       Monitors [7.7]
◦ The basic element in the monitor class are:                                                       ◦ The main part of the solution appears quite simple:
  monitor dp                                                                                             db.pickup(i);
  {                                                                                                      ...
    enum { philosophising, hungry, eating }                                                              dine
      state[5];                                                                                          ...
    condition self[5];                                                                                   db.putdown(i);
    void pickup(int i);
    void putdown(int i);
    void test(int i);
    void init() {
      for (int i = 0; i < 5; i++)
      state[i] = philosophising;
    }
  }

                                     CP2002   Higher Level Mechanisms   Monitors [7.7] – p.33/102                                          CP2002   Higher Level Mechanisms   Monitors [7.7] – p.34/102




               Monitors [7.7]                                                                                       Monitors [7.7]
◦ The member functions are implemented as:                                                            void test(int i) {
                                                                                                        if ( (state[(i + (5-1)) % 5] != eating) &&
  void pickup(int i) {
                                                                                                             (state[i] == hungry) &&
    state[i] = hungry;
                                                                                                             (state[(i + 1) % 5] != eating) ) {
    test[i];
                                                                                                          state[i] = eating;
    if (state[i] != eating)
                                                                                                          self[i].signal();
    self[i].wait();
                                                                                                        }
  }
                                                                                                      }
  void putdown(int i) {                                                                             ◦ Note: in the code fragments just presented, expressions
    state[i] = philosophising;                                                                        such as (i + 4)%5 were rewritten as (i + (5 − 1))%5 to
    test((i+(5-1)) % 5);                                                                              emphasise that the argument is referring to the previous
    test((i+1) % 5);                                                                                  table place. Of course, expressions such as (i + 1)%5
  }                                                                                                   refer to the next table place.


                                     CP2002   Higher Level Mechanisms   Monitors [7.7] – p.35/102                                          CP2002   Higher Level Mechanisms   Monitors [7.7] – p.36/102
                Monitors [7.7]                                                                                         Monitors [7.7]
◦ The sequence of {db.pickup(i) ... dine ... db.putdown(i)}                                              As mentioned earlier, the monitor construct guarantees
  may result in the suspension of the philosopher process                                                that only one code fragment is active within the monitor
  at pickup but once any conflict with a neighbour clears,                                                at any time (through use of a mutex). If a currently
  the philosopher resumes and goes on to dine.                                                           active code fragment completes a call to one of the
                                                                                                         member functions, we would like any previously blocked
◦ This solution ensures that no two neighbours are eating                                                thread to resume. Therefore, the member functions
  simultaneously, that more than one philosopher can eat,                                                typically contain a wrapper such as the following:
  and that no deadlocks can occur. However,
  philosophers can still starve.                                                                         wait(mutex);
                                                                                                         ...
                                                                                                         body of F;
                                                                                                         ...
                                                                                                         if (next_count > 0)
                                                                                                           signal(next)
                                                                                                         else
                                                                                                           signal(mutex);
                                      CP2002   Higher Level Mechanisms   Monitors [7.7] – p.37/102                                           CP2002     Higher Level Mechanisms     Monitors [7.7] – p.38/102




                Monitors [7.7]                                                                                         Monitors [7.7]
◦ Observe that after the critical section is handled, a
  next_count variable is tested — other processes that                                                   Resource allocation: The idea of making decisions at
  might have been blocked by this mutex will have done a                                                 the point where a wait() returns, and actually deciding
  wait on next, incremented next_count, and in effect                                                    which of a number of blocked processes will be the one
  been queued. The exit section of this code fragment                                                    to resume, is essentially an issue of resource allocation.
  can pass mutually exclusive access to the monitor onto                                                 Silberschatz shows a code fragment for a monitor
  the next blocked process via either a signal(next), or a                                               called ResourceAllocation and it suggests the use of a
  simple signal(mutex) completes the member function.                                                    SJF algorithm to select the process to resume.
◦ Note: the compiler is responsible for the implementation
  of the monitor so it (and not the user) will organise
  mutex handling. It will also have code to handle
  resumption of previously blocked processes or threads
  etc. If some form of priority is desired when handling
  process resumption, the wait calls in the condition
  constructs can be defined to have an input argument n
  to allow priority specification e.g. x.wait(n).
                                      CP2002   Higher Level Mechanisms   Monitors [7.7] – p.39/102                                           CP2002     Higher Level Mechanisms     Monitors [7.7] – p.40/102




                Monitors [7.7]                                                                       Operating System Synchronisation [7.8]
  Final comments on monitor use:                                                                         The Solaris 2 operating system was designed to
◦ Programmers must still be careful when using monitor                                                   provide some elements of real-time computing, to be
  constructs. In particular, the member functions must be                                                multithreaded, and to have SMP.
  called in their proper order.                                                                        ◦ Implements a variety of locks to support multitasking,
◦ Tanenbaum emphasises the role of the compiler in                                                       multithreading (including real-time threads), and
  handling mutex correctly, so that the programmer using                                                 multiprocessing.
  monitor member functions will never execute critical                                                 ◦ Implements semaphores and condition variables as
  regions at the same time. Also, Tanenbaum briefly                                                       discussed here.
  mentions that it is possible to implement monitor
  member functions without having the signal(mutex)
  present as the last statement.




                                      CP2002   Higher Level Mechanisms   Monitors [7.7] – p.41/102                                             CP2002      Operating System Synchronisation [7.8] – p.42/102
Operating System Synchronisation [7.8]                                                                 Operating System Synchronisation [7.8]
  ◦ Uses adaptive mutexes to protect access to every                                                     ◦ Uses condition variables and semaphores if the data to
    critical data item.                                                                                    protect involves longer code segments.
        An adaptive mutex starts as a standard semaphore                                                 ◦ Uses readers-writers locks to protect data that are
        implemented as a spinlock.                                                                         accessed frequently, but mainly in a read-only manner.
        On an MP system where the thread holding the lock                                                  This is more efficient than a semaphore which would
        is not currently in a run state, the thread will block                                             serialise accesses and allow only one access at a time.
        and sleep. If the thread holding the lock is currently                                             As readers-writers locks are more costly to implement
        running on another processor (!), the thread will                                                  (in terms of run-time effort), they are usually reserved
        spinlock based on the assumption that the lock will                                                for protection on long sections of code.
        clear relatively soon.                                                                           ◦ Uses turnstiles to order the list of threads waiting to
        On a uni-processor system, the thread will sleep                                                   acquire either an adaptive mutex or reader-writer lock:
        immediately since the other thread must resume
        running on the CPU in order for the lock to clear.

                                          CP2002   Operating System Synchronisation [7.8] – p.43/102                                             CP2002   Operating System Synchronisation [7.8] – p.44/102




Operating System Synchronisation [7.8]                                                                 Operating System Synchronisation [7.8]
       Every object that requires synchronised access will                                                 The Windows 2000 operating system is a multithreaded
       have a lock owned by a thread — if the thread no                                                    kernel that also claims to support real-time applications
       longer exists or wants access to the object, the                                                    and multiple processors.
       kernel passes ownership of the lock onto another                                                  ◦ Uses interrupt masks to protect access to global
       thread.                                                                                             resources on uniprocessor systems.
       To avoid priority inversion, Solaris 2 implements a
                                                                                                         ◦ Uses spinlocks on multiprocessor systems, for small
       priority inheritance protocol.
                                                                                                           code segments.
       To optimise Solaris 2 performance, developers
       continually refine locking methods and users                                                       ◦ For thread synchronisation outside of the kernel, a
       typically do performance tuning.                                                                    mechanism called dispatcher objects is provided. It can
                                                                                                           use mutexes, semaphores and events. An event acts
                                                                                                           like a condition variable in the sense that it can cause a
                                                                                                           wait and also send a signal.


                                          CP2002   Operating System Synchronisation [7.8] – p.45/102                                             CP2002   Operating System Synchronisation [7.8] – p.46/102




Comments on Atomic Transactions [7.9]                                                                  Comments on Atomic Transactions [7.9]
    Aspects of data base operation and file system                                                        ◦ File systems can be thought of as a shared data
    operation share ideas of resource allocation that we                                                   resource that must have its internal structure kept
    have seen in process synchronisation.                                                                  consistent while requests for reads and writes are
  ◦ The readers-writers problem is perhaps the most                                                        serviced.
    relevant from a database viewpoint.                                                                  ◦ As data must be updated, the question arises how do
  ◦ Our discussion of monitors has shown how they can be                                                   we handle these changes. We would like updates to be
    used to allow single access to a resource i.e. serialised                                              performed in an atomic way, but what can be done to
    access, with the return of the wait() even providing an                                                handle system failure e.g. loss of power, etc.
    ability to implement priority resource allocation
    strategies.
  ◦ In operating system studies, there has been some use
    of database ideas in guaranteeing robustness.


                                          CP2002   Comments on Atomic Transactions [7.9] – p.47/102                                              CP2002   Comments on Atomic Transactions [7.9] – p.48/102
Comments on Atomic Transactions [7.9]                                                                               Comments on Atomic Transactions [7.9]
        Some work originating at the Computer Systems                                                                 ◦ The operating system has in effect got updates of the
        Research Group of the University of California,                                                                 file system detached in time and can schedule it
        Berkeley a , led to the soft updates approach to                                                                according to other system needs, yet the integrity is
        maintaining file system integrity.                                                                               guaranteed (soft updates says that the meta data and
   ◦ The idea is that all updates to the directory structure of                                                         data is either on the disk waiting to be processed, or not
     the file system is written to a cache on the storage                                                                on the disk ... either way, it is consistent).
     media, along with any new data, and then a background                                                            ◦ By not deleting this meta data, the system can actually
     process manipulates data pointers etc. to get this                                                                 recreate its file system at different check points over
     information into its final form.                                                                                    time.
   a
       This group created the Berkeley Software Distribution of UNIX, normally re-
 ferred to as BSD.




                                                        CP2002   Comments on Atomic Transactions [7.9] – p.49/102                                             CP2002   Comments on Atomic Transactions [7.9] – p.50/102




Comments on Atomic Transactions [7.9]                                                                               Comments on Atomic Transactions [7.9]
        In the linux world, the relatively poor performance of the                                                      Embedded System: An example of a file server
        ex2fs file system has led to a number of log based                                                               supporting multiple client operating systems, and
        approaches to work around the issue of how to handle                                                            featuring user access to check points, is the NetApp
        reconstruction of a file system after a crash. There have                                                        system.
        been positive reports of these systems to date.                                                                    These file servers are not exactly cheap but are very
   ◦ The idea is to create a consistent log of the transactions                                                            powerful as users can access, in real-time,
     on the disk so that a file system reconstruction is more                                                               snapshots of their files saved on an hourly basis over
     complete.                                                                                                             a day, on a daily basis over a few weeks, and over a
                                                                                                                           monthly basis over a year or so.
                                                                                                                           In university environments (where students do
                                                                                                                           sometimes delete wanted files), these file servers
                                                                                                                           can prevent system administrators from developing
                                                                                                                           the more tender aspects of their personalities. Oh -
                                                                                                                           they also give students their files back.
                                                                                                                           See http://www.netapp.com for details.
                                                        CP2002   Comments on Atomic Transactions [7.9] – p.51/102                                             CP2002   Comments on Atomic Transactions [7.9] – p.52/102




                               Summary                                                                                                    Summary
        Important concepts have included critical sections with                                                         A number of classical synchronisation problems were
        an entry section, a critical section, an exit section, and a                                                    presented (and not just so nerds would now have
        remainder section;                                                                                              classical conversation lines for parties). Chopstick
        A solution to the critical section problem, that was suited                                                     etiquette has also been improved.
        for multiple processor implementation, shed light on the                                                        The idea that a return from a wait() allows the operating
        fundamentals of modern day deli customer service.                                                               system to select which of a number of processes
        We have addressed mutual exclusion with                                                                         blocked on the same event may resume, provides an
        software-only and hardware-software implementations.                                                            interesting degree of flexibility in system operation. This
                                                                                                                        idea may be available in some user thread models too.
        Semaphores were introduced, and then the distinction
        of blocking via a spinlock versus choosing to put the
        process into a sleep was described.



                                                                              CP2002         Summary – p.53/102                                                                     CP2002         Summary – p.54/102
                  Deadlocks [8]                                                                                   Deadlocks: Introduction
Intent: In a multi-process (or threaded) computing                                                          In typical computing applications, a process needs
environment, several processes may compete for a finite                                                      exclusive access to more than one resource. For
number of resources. A process requests resources and, if                                                   example, two processes may be launched to input
they are unavailable, the process enters a wait state. A set                                                image data and print it so both processes need access
of processes is deadlocked if each process in the set is                                                    to a digital camera and a printer.
waiting for a resource that only another process in the set                                               ◦ If process A acquires access to the digital camera while
can release. In this part of the course, we investigate the                                                 process B acquires access to the printer, then each
types of deadlock and look at ways to handle it.                                                            process will next try to acquire the other necessary
                                                                                                            resource ... and fail. Until the resource needed is
                                                                                                            released, a process needing that resource will sleep.
                                                                                                          ◦ As the held resources are associated with sleeping
                                                                                                            processes, there is no chance for the process to
                                                                                                            release the resource and so deadlock has occurred.

                                                                   CP2002      Deadlocks [8] – p.55/102                                            CP2002   Deadlocks [8]   Deadlocks: Introduction – p.56/102




         Deadlocks: Introduction                                                                                              Resources
 ◦ If each resource was attached to a separate computing                                                    Computer resources are partitioned into a number of
   node, then we have also described a case of distributed                                                  types e.g. memory, storage space, I/O devices, CPU
   deadlock.                                                                                                time.
   We describe deadlocks and characterise them.                                                           ◦ If a user requests an instance of a resource type, the
   We study methods for handling deadlocks, including                                                       allocation of any instance of that type will satisfy the
   prevention and avoidance as well as detection and                                                        request. If it will not, then we must further classify the
   recovery.                                                                                                resources. Example: if a user requests a computer and
                                                                                                            is given a PC running windoze, then additional
   First, we review resource allocation mechanisms since                                                    classification (and education) is necessary.
   it is deadlock in resource acquisition that is at the root
   of this problem.




                                          CP2002   Deadlocks [8]    Deadlocks: Introduction – p.57/102                                                      CP2002      Deadlocks [8]   Resources – p.58/102




                     Resources                                                                                                Resources
   Resources come in two types:
                                                                                                            The normal sequence of events required to use a
 ◦ A preemptable resource is one that can be taken away
                                                                                                            resource is:
   from the process owning it. Memory is a good example
   of a preemptable resource — if a process is using all                                                  ◦ request the resource — if access cannot be granted
   the physical memory in a computer, and another                                                           immediately, then the requesting process will usually
   process is about to run, the first process can give up                                                    wait;
   some of its physical memory by being swapped out.                                                      ◦ use the resource;
 ◦ A nonpreemptable resource is one that cannot be taken                                                  ◦ release the resource.
   away from the current owner without causing the
   computation to fail. An example of a nonpreemptable                                                      Examples of the request and release of resources
   resource is a CD writer that is in the process of writing a                                              include some system calls studied early in the course:
                                                                                                            file open and file close; allocate and free memory;
   CD and which another process wishes to acquire.
                                                                                                            request and release device.
   In general, deadlocks involve nonpreemptable
                                                                                                            More recent examples are exclusive resource access
   resources (a deadlock could occur with a preemptable
                                                                                                            managed by the wait() and signal() operations.
   resource but it is trivial to clear).
                                                   CP2002      Deadlocks [8]     Resources – p.59/102                                                       CP2002      Deadlocks [8]   Resources – p.60/102
                      Resources                                                                                                       Deadlock Characterisation [8.2]
  The operating system tracks resource allocation.
                                                                                                                                       Coffman et al showed in 1971 that the following four
◦ For each instance of use, the operating system checks                                                                                conditions are required for there to be a deadlock:
  that the process involved has requested and been
                                                                                                                                  ◦ Mutual exclusion — at least one resource must be held
  allocated the resource.
                                                                                                                                    in a nonsharable mode i.e. single use. If another
◦ If a process requests a resource allocated to another                                                                             process requests this resource, it must wait until the
  process, it can be added to a queue of processes                                                                                  resource is released;
  waiting for the resource (if the process can do no work
                                                                                                                                  ◦ Hold and Wait — a process must be holding at least
  in the meantime, it can block itself and sleep).                                                                                  one resource and waiting to acquire additional
  A set of processes is in a deadlock state when every                                                                              resources that are currently held by other processes;
  process in the set is waiting for an event that can be
  only caused by another process in the set.
◦ A multithreaded application is a good candidate for
  deadlocks because multiple threads can compete for
  shared resources.
                                                                            CP2002       Deadlocks [8]   Resources – p.61/102                                                                      CP2002      Deadlocks [8]    Deadlock Characterisation [8.2] – p.62/102




  Deadlock Characterisation [8.2]                                                                                                          Resource Allocation Graph
                                                                                                                                       Recall that the definition for deadlock states that
◦ No preemption — resources not being preemptable                                                                                      deadlock occurs “if each process in the set is waiting for
  means that their release is only voluntary by the                                                                                    a resource that only another process in the set can
  process holding the resource;                                                                                                        release”.
◦ Circular Wait — a set of n+1 waiting processes                                                                                  ◦ For a system comprising processes {P _1, P _2} and
  {P _0, P _1, . . . P _n} must exist in which P _0 is waiting for                                                                  resources {R_1, R_2}, a (contrived) deadlock example is
  a resource from P _1, P _1 is waiting for a resource from                                                                         process P _1 wants resource R_1 which is allocated to
  P _2, P _n − 1 is waiting for a resource from P _n, and                                                                           process P _2 which wants resource R_2 which is
  P _n is waiting for a resource from P _0,                                                                                         allocated to process P _1.
  Note: all 4 conditions must occur.                                                                                              ◦ If you think about this description, you will see that it
                                                                                                                                    satisfies the definition.
                                                                                                                                  ◦ However, a graphical method of representing the
                                                                                                                                    resource “belongings” (or allocations) and the process
                                                                                                                                    “longings” (or resource needs) will show up circular
                                                                                                                                    dependencies more clearly.
                                                        CP2002      Deadlocks [8]    Deadlock Characterisation [8.2] – p.63/102                                          CP2002   Deadlocks [8]   Deadlock Characterisation [8.2]   Resource Allocation Graph – p.64/102




      Resource Allocation Graph                                                                                                            Resource Allocation Graph
  We use a directed graph called a system                                                                                         ◦ We have specifically chosen the direction of the arrow
  resource-allocation graph to show dependencies                                                                                    for a request, as P-to-R, and for an assignment, as
  between elements in a computing system. It comprises:                                                                             R-to-P, such that a circular dependency can be
◦ a set of vertices and a set of edges;                                                                                             highlighted and thus we more readily see the conditions
                                                                                                                                    needed for a deadlock.
◦ each vertex is either a process P _i or a resource type
  R_i;                                                                                                                            ◦ Hand-waving-explanation: Actually, the arrows also
                                                                                                                                    happen to point in the direction of dependency since a
◦ each edge is either a resource request edge such as                                                                               process longing for (and maybe blocking until it gets) a
  P _i → R_j or a resource assignment edge such as                                                                                  resource is a case where P depends on an R and also
  R_j → P _i;                                                                                                                       because a resource belonging to a process happens to
                                                                                                                                    depend on that process to relinquish it before it can be
                                                                                                                                    used elsewhere i.e. this R depends on the P that it
                                                                                                                                    belongs to. Hands may now return to pockets a .

                                                                                                                                  a
                                                                                                                                      Unless kilts or equivalent have been worn.
                              CP2002   Deadlocks [8]   Deadlock Characterisation [8.2]    Resource Allocation Graph – p.65/102                                           CP2002   Deadlocks [8]   Deadlock Characterisation [8.2]   Resource Allocation Graph – p.66/102
     Resource Allocation Graph                                                                                                     Resource Allocation Graph
  We now show a typical resource-allocation graph:                                                                              The processes are represented as a circle and the
                                                                                                                                resources are represented as boxes.
                                                                                                                                The dark dots inside each resource indicate how many
                                                                                                                                instances of that resource are present for use — for this
                                                                                                                                reason, we also sometimes talk of resource types and
                                                                                                                                resource instances.
                                                                                                                                In the graph shown, the sets of processes P, resources
                                                                                                                                R, and edges E are:
                                                                                                                              ◦ P = {P _1, P _2, P _3};
                                                                                                                              ◦ R = {R_1, R_2, R_3, R_4};
           Fig.20 Resource-Allocation Graph
                                                                                                                              ◦ E = {P1 →R1 , P2 →R3 , R1 →P2 , R2 →P2 , R2 →P1 , R3 →P3 }.


                            CP2002   Deadlocks [8]   Deadlock Characterisation [8.2]   Resource Allocation Graph – p.67/102                               CP2002   Deadlocks [8]   Deadlock Characterisation [8.2]   Resource Allocation Graph – p.68/102




     Resource Allocation Graph                                                                                                     Resource Allocation Graph
  Resource instances: 1 × R1 , 2 × R2 , 1 × R3 , 3 × R4 .                                                                       As mentioned earlier, the choice of arrow direction
◦ Important: when searching for circular dependencies,                                                                          means that if the graph contains no cycles (circular
  we will have to take into account the presence of spare                                                                       paths), then no process in the system is deadlocked. If
  resources since unallocated resources are a great way                                                                         a cycle exists, a deadlock may exist.
  to solve resource allocation problems!                                                                                      ◦ If each resource type has only one instance, then a
  Process states: process P1 holds one R2 and is waiting                                                                        deadlock will exist. In general, we look for cycles in the
  for one R1 ; process P2 holds one R1 and one R2 , and is                                                                      graph and then check the number of resources
  waiting for one R3 ; process P3 holds one R3 .                                                                                instances available at each resource vertex to
                                                                                                                                determine if a process is deadlocked.
◦ If a resource request edge is satisfied, the arrow is
  replaced by one in the opposite direction. If an instance                                                                     We now show a resource-allocation graph with a cycle.
  of resource use finishes, the assignment edge is                                                                               Suppose process P3 requests an instance of resource
  deleted.                                                                                                                      type R2 — as no resource instance is currently
                                                                                                                                available, a request edge P3 → R2 is added:

                            CP2002   Deadlocks [8]   Deadlock Characterisation [8.2]   Resource Allocation Graph – p.69/102                               CP2002   Deadlocks [8]   Deadlock Characterisation [8.2]   Resource Allocation Graph – p.70/102




     Resource Allocation Graph                                                                                                     Resource Allocation Graph
                                                                                                                                Two minimal cycles exist in the new system:
                                                                                                                                P1 → R1 → P2 → R3 → P3 → R2 → P1 ;
                                                                                                                                P2 → R3 → P3 → R2 → P2 .
                                                                                                                              ◦ A minimal cycle means it contains a basic cycle and no
                                                                                                                                gratuitous (repetitive) extra cycles.
                                                                                                                              ◦ In this case, all resource instances are allocated to the
                                                                                                                                3 processes which are all in wait states while waiting for
                                                                                                                                new resources to be freed for reuse. We have deadlock.
    Fig.21 Resource-Allocation Graph with deadlock                                                                              Now consider a system where all resources are
                                                                                                                                allocated but some currently belong to processes that
                                                                                                                                are not part of a cycle.



                            CP2002   Deadlocks [8]   Deadlock Characterisation [8.2]   Resource Allocation Graph – p.71/102                               CP2002   Deadlocks [8]   Deadlock Characterisation [8.2]   Resource Allocation Graph – p.72/102
      Resource Allocation Graph                                                                                                     Resource Allocation Graph
                                                                                                                                 A minimal cycle exists in this system:
                                                                                                                                 P1 → R1 → P3 → R2 → P1 .
                                                                                                                               ◦ However, process P4 can relinquish its instance of
                                                                                                                                 resource R2 when it is finished running (it is not waiting
                                                                                                                                 therefore it can be running).
                                                                                                                                 Summary:
                                                                                                                               ◦ If the resource-allocation graph contains no cycles, the
  Fig.22 Resource-Allocation Graph with a cycle but no                                                                           system is not in a deadlock state.
                       deadlock                                                                                                ◦ If there is a cycle, there may be a deadlock — it
                                                                                                                                 depends on the number of resources available in the
                                                                                                                                 system.



                           CP2002   Deadlocks [8]   Deadlock Characterisation [8.2]   Resource Allocation Graph – p.73/102                                CP2002   Deadlocks [8]   Deadlock Characterisation [8.2]   Resource Allocation Graph – p.74/102




Methods for Handling Deadlocks [8.3]                                                                                          Methods for Handling Deadlocks [8.3]
   Ensure that the system will never enter a deadlock                                                                            Allow the system to enter a deadlock state and then
   state:                                                                                                                        recover.
 ◦ In deadlock prevention, methods are employed to                                                                             ◦ The system now requires an algorithm to analyse
   ensure that at least one of the 4 necessary conditions                                                                        system state and either kill selected processes or
   for deadlock cannot occur. This solution involves                                                                             preempt some resources (a process which has lost a
   constraining resource requests.                                                                                               resource may not be able to continue).
 ◦ In deadlock avoidance, additional information about                                                                           Ignore the problem and pretend that deadlocks never
   overall process resource requirements is used to decide                                                                       occur (or only very rarely occur in the system. This
   for each request whether or not the request should wait.                                                                      approach is used by most operating systems.
                                                                                                                               ◦ In real-time systems, it might be the case that the high
                                                                                                                                 priority real-time processes can continue to operate in
                                                                                                                                 spite of the fact that the lower priority processes are
                                                                                                                                 deadlocked!

                                                CP2002     Deadlocks [8]    Methods for Handling Deadlocks [8.3] – p.75/102                                                    CP2002     Deadlocks [8]    Methods for Handling Deadlocks [8.3] – p.76/102




       Deadlock Prevention [8.4]                                                                                                     Deadlock Prevention [8.4]
   We consider how to invalidate each of the 4 necessary                                                                         To ensure that Hold and Wait never occurs in the
   conditions for deadlock in order to prevent it.                                                                               system, we must guarantee that whenever a process
   Mutual Exclusion is not relevant to sharable resources                                                                        requests a resource, it does not hold any other
   (which do not block on multiple access). However,                                                                             resources.
   nonsharable resources must be accessed in a mutually                                                                        ◦ One approach is to require each process to request and
   exclusive way so this condition can not usually be                                                                            be allocated all resources before it begins execution, or
   avoided.                                                                                                                      allow the process to request resources only when the
                                                                                                                                 process has none. In this later scenario, the process
                                                                                                                                 would release all existing resources before requesting
                                                                                                                                 new resources (and possibly re-acquiring some of its
                                                                                                                                 original resources).




                                                           CP2002     Deadlocks [8]    Deadlock Prevention [8.4] – p.77/102                                                               CP2002     Deadlocks [8]    Deadlock Prevention [8.4] – p.78/102
      Deadlock Prevention [8.4]                                                                               Deadlock Prevention [8.4]
◦ A disadvantage is that resource utilisation is lowered                                                 We can break the no preemption condition as follows.
  since more effort is directed to (re-)allocation.                                                    ◦ If a process that is holding some resources requests
  Silberschatz suggests that starvation is now possible                                                  another resource that cannot be immediately allocated
  but it seems to PM while this might now occur instead                                                  to it, then it releases all currently allocated resources.
  of some previously deadlocked processes, there may
  now also be some processes able to run.                                                              ◦ The preempted resources are added to the list of
                                                                                                         resources that the process is waiting on, and the
                                                                                                         process will restart only when it can regain its original
                                                                                                         resources and the new ones.
                                                                                                       ◦ Alternatively, instead of deallocating the current
                                                                                                         resources, we can mark them as available for
                                                                                                         preemption. In effect, all process that are about to enter
                                                                                                         a wait state are allowed to “cannibalise” any resources
                                                                                                         associated with other waiting processes. Again, this
                                                                                                         may help at least one process not wait.
                                       CP2002   Deadlocks [8]   Deadlock Prevention [8.4] – p.79/102                                                     CP2002      Deadlocks [8]   Deadlock Prevention [8.4] – p.80/102




      Deadlock Prevention [8.4]                                                                               Deadlock Avoidance [8.5]
  The circular wait condition can be avoided if all                                                      The simplest and most useful model requires that each
  resource allocation requests are ordered according to a                                                process declare the maximum number of resources of
  strict enumeration of resources.                                                                       each type that it may need.
◦ The idea is that all processes request resources in the                                              ◦ The deadlock avoidance algorithm then dynamically
  same order and therefore clash at the first request for a                                               examines the resource allocation state to ensure that
  common resource that they need.                                                                        there can never be a circular wait condition.
◦ That is, this prevents any two processes each from                                                   ◦ The resource allocation state is defined by the number
  holding some resources needed by the other.                                                            of available and allocated resources, and the maximum
                                                                                                         demands of the processes. Notice that it requires some
                                                                                                         additional a priori information about resource use.




                                       CP2002   Deadlocks [8]   Deadlock Prevention [8.4] – p.81/102                                                     CP2002      Deadlocks [8]    Deadlock Avoidance [8.5] – p.82/102




       Deadlock Avoidance [8.5]                                                                                      Safe State [8.5.1]
  A more complex approach is to consider the time                                                        A system state is safe if the system can allocate
  intervals during which the processes may need                                                          resources to each process, up to its stated maximum, in
  common resources and see if the time intervals can be                                                  some order and still avoid a deadlock.
  made non-overlapping.                                                                                ◦ The idea is that each new process is only launched
◦ This requires even more information than the previous                                                  when it is known that the existing pool of unallocated
  approach, and is less practical!                                                                       resources plus any resources already allocated to
                                                                                                         currently running (independent) processes are sufficient
                                                                                                         to allow the new process to complete. If insufficient
                                                                                                         resources are available, the new process is held until
                                                                                                         resources become available (from existing processes
                                                                                                         that finish).




                                       CP2002   Deadlocks [8]   Deadlock Avoidance [8.5] – p.83/102                                     CP2002   Deadlocks [8]    Deadlock Avoidance [8.5]   Safe State [8.5.1] – p.84/102
               Safe State [8.5.1]                                                                                                         Safe State [8.5.1]
◦ The formal statement is that a system is in a safe state                                                                    When a process requests an available resource,
  only if these exists a safe sequence. A sequence of                                                                         system must decide if immediate allocation leaves the
  processes {P1 , P2 , ...Pn } is a safe sequence for the                                                                     system in a safe state.
  current allocation state if, for each Pi , the resources that                                                             ◦ If Pi resource needs are not immediately available, then
  Pi can still request can be satisfied by the currently                                                                       Pi can wait until all Pj have finished. When Pj is
  available resources plus the resources held by all of the                                                                   finished, Pi can obtain needed resources, execute,
  Pj ; j < i.                                                                                                                 return allocated resources, and terminate.
                                                                                                                            ◦ When Pi terminates, Pi+1 can obtain its needed
                                                                                                                              resources, and so on.




                                    CP2002     Deadlocks [8]   Deadlock Avoidance [8.5]   Safe State [8.5.1] – p.85/102                                                CP2002      Deadlocks [8]   Deadlock Avoidance [8.5]    Safe State [8.5.1] – p.86/102




               Safe State [8.5.1]                                                                                         Resource Allocation Graph Alg. [8.5.2]
                                                                                                                              For systems with only one instance of each resource, a
  If a system is in a safe state, no deadlock can occur.                                                                      variant of the resource allocation graph can be used to
  If a system is in an unsafe state, there is a possibility of                                                                avoid deadlocks.
  deadlock.                                                                                                                   In addition to request edges and assignment edges, we
  Avoidance ensures that a system will never enter an                                                                         introduce a claim edge which represents a future
  unsafe state. In effect, by applying the rule before each                                                                   request.
  new process is launched, we are performing an                                                                             ◦ A claim edge is drawn as a dashed line.
  incremental optimisation that ensures that a “safety”
                                                                                                                            ◦ When a claim edge converts into a request later, it
  objective function cannot go “negative”.
                                                                                                                              becomes a normal line. The system will prevent the
                                                                                                                              request by putting the process into a wait state if the
                                                                                                                              new request would create a cycle.
                                                                                                                            ◦ When a resource is released by a process, the
                                                                                                                              assignment edge reconverts to a claim edge.
                                                                                                                              Resources must be claimed a priori in the system.
                                    CP2002     Deadlocks [8]   Deadlock Avoidance [8.5]   Safe State [8.5.1] – p.87/102                               CP2002   Deadlocks [8]    Deadlock Avoidance [8.5]   Resource Allocation Graph Alg. [8.5.2] – p.88/102




       Bankers Algorithm [8.5.3]                                                                                                  Bankers Algorithm [8.5.3]
  For systems with more than one instance of each                                                                             Three or Four data structures are maintained to
  resource, the Bankers Algorithm can be used.                                                                                implement this algorithm for a system of n processes
◦ When a new process enters the system, it must declare                                                                       and m resource types:
  the maximum number of instances of each resource                                                                          ◦ Vector available[j], size m, holds the number of available
  type that it may need. This number must not exceed                                                                          resources of each type;
  total system resources.                                                                                                   ◦ Array max[i,j], size n by m, holds the maximum demand
◦ When a process requests a set of resources, the                                                                             of each process on each resource type. If max[i,j]=k,
  system must determine if the allocation of these                                                                            then process Pi may request at most k instances of
  resources will leave the system in a safe state. If it will,                                                                resource type Rj ;
  the resources are allocated; otherwise, the process                                                                       ◦ Array allocation[i,j], size n by m, holds the number of
  must wait until some other processes release enough                                                                         resources of each type currently allocated in the
  resources.                                                                                                                  system. If each process suddenly requested its
                                                                                                                              maximum amount of resources, then this array would
                                                                                                                              equal max[,];
                               CP2002   Deadlocks [8]   Deadlock Avoidance [8.5]   Bankers Algorithm [8.5.3] – p.89/102                                         CP2002     Deadlocks [8]    Deadlock Avoidance [8.5]   Bankers Algorithm [8.5.3] – p.90/102
        Bankers Algorithm [8.5.3]                                                                                                             Deadlock Detection [8.6]
  ◦ Array need[i,j] holds the remaining resource count                                                                                  If a system cannot prevent deadlocks, then it needs to
    needed for each process to reach its maximum                                                                                        be able to detect them and have a recovery algorithm.
    allocation i.e. need[,] = max[,]-allocation[,].                                                                                     The detection of deadlocks is a run-time load on the
    We will practice this technique in the next tutorial: safety                                                                        system.
    test algorithm, resource request algorithm.                                                                                         The recovery algorithm will usually involve deletion of
  ◦ Silberschatz (6th edition): pages 258-259.                                                                                          some processes.




                                      CP2002     Deadlocks [8]   Deadlock Avoidance [8.5]    Bankers Algorithm [8.5.3] – p.91/102                                                                       CP2002        Deadlocks [8]   Deadlock Detection [8.6] – p.92/102




Single Instance of Each Resource Type                                                                                               Single Instance of Each Resource Type
    This algorithm uses a modification of the resource                                                                                   The system must periodically invoke the algorithm that
    allocation graph called a wait-for graph.                                                                                           searches for a cycle in the graph.
  ◦ As each resource type has only one instance, the                                                                                  ◦ An algorithm to detect a cycle in a graph requires an
    resource nodes can be removed.                                                                                                      order of n2 operations, where n is the number of
  ◦ An edge in the wait-for graph from Pi to Pj means that                                                                              vertices in the graph.
    process Pi is waiting for Pj to complete.                                                                                           Comment: it appears that the original resource
  ◦ A cycle found in the wait-for graph means a deadlock                                                                                allocation graph could also be used. See Silberschatz
    exists.                                                                                                                             Figure 8.7.




                            CP2002   Deadlocks [8]   Deadlock Detection [8.6]   Single Instance of Each Resource Type – p.93/102                                CP2002    Deadlocks [8]    Deadlock Detection [8.6]     Single Instance of Each Resource Type – p.94/102




Single Instance of Each Resource Type                                                                                               Several Instances of a Resource Type
                                                                                                                                        This algorithm uses a modification of the bankers
                                                                                                                                        algorithm.
                                                                                                                                      ◦ It retains the data structures for available[] and
                                                                                                                                        allocation[], and introduces array request[i,j], of size n
                                                                                                                                        by m, where request[i,j]=k means that process Pi is
                                                                                                                                        requesting k more instances of resource Rj .
   Fig.23 Resource Allocation Graph, and corresponding                                                                                  This algorithm performs a global search of whether
              wait-for Graph (OSC Fig. 8.7)                                                                                             there is any process that needs a resources and which
                                                                                                                                        can obtain them in order top continue execution.
                                                                                                                                        Examples will be provided in the tutorial.




                            CP2002   Deadlocks [8]   Deadlock Detection [8.6]   Single Instance of Each Resource Type – p.95/102                                 CP2002    Deadlocks [8]    Deadlock Detection [8.6]     Several Instances of a Resource Type – p.96/102
  Detection Algorithm Detection                                                                                               Detection Algorithm Detection
  How often should the deadlock detection algorithm be                                                                        If the detection algorithm is run infrequently, it may be
  run? The answer depends on:                                                                                                 difficult to identify the locked process as all processes
◦ the frequency of deadlocks; and                                                                                             might have large CPU use statistics.
◦ the number of processes that will be affected.                                                                              One suggestion is to run the detection every half an
                                                                                                                              hour or more often if system load is say below 40%.
  If the detection algorithm is run too frequently, it could
  contribute significant load on the system (the algorithms
  are usually order n2 ).




                            CP2002   Deadlocks [8]    Deadlock Detection [8.6]   Detection Algorithm Detection – p.97/102                                CP2002   Deadlocks [8]    Deadlock Detection [8.6]   Detection Algorithm Detection – p.98/102




   Recovery from Deadlock [8.7]                                                                                                Recovery from Deadlock [8.7]
  There are a number of ways to clear a deadlock:                                                                                In what order are processes aborted?
◦ Obtain a skilled human being and appoint this person                                                                           What is the priority of the process.
  “chief deadlock unlocker”. This may be expensive.                                                                              For how long has the process computed, and/or how
◦ Let the system recover automatically.                                                                                          much longer does it need to complete.
                                                                                                                                 How many and what type of resources the process
  For process termination, the options are:
                                                                                                                                 has used.
◦ Abort all deadlocked processes, with costs such as lost                                                                        Also need to know how many and what type of
  results;                                                                                                                       resources the process needs to complete.
◦ Abort one process at a time until the deadlock cycle is                                                                        How many processes will need to be terminated.
  eliminated, which may minimise losses from process                                                                             Is the process interactive or batch?
  termination but does require a little more run-time
  processing for the deadlock detection algorithm. Issues
  for consideration:

                                                     CP2002     Deadlocks [8]     Recovery from Deadlock [8.7] – p.99/102                                                         CP2002    Deadlocks [8]     Recovery from Deadlock [8.7] – p.100/102




   Recovery from Deadlock [8.7]                                                                                                                 Summary
  In resource preemption, we remove individual                                                                                Handling deadlocks can combine the three basic
  resources and give them to other processes until the                                                                        approaches of prevention, avoidance, and detection,
  deadlock is broken. If preemption is dealing with                                                                           and allow the use of the optimal approach for each
  deadlocks, we must consider:                                                                                                resource in the system.

◦ Selecting a victim — wish to minimize cost.                                                                                 Partition resources into hierarchically ordered classes.
                                                                                                                            ◦ Use the most appropriate technique for handling
◦ Rollback returns a process that has lost a resource
  back to some safe state. The process will need to have                                                                      deadlocks within each class.
  been specially coded to make snapshots from which to                                                                        Recall that there are 4 conditions necessary for
  resume.                                                                                                                     deadlock: mutual exclusion, hold and wait, no
◦ Starvation is possible if the same process is always                                                                        preemption, and circular wait.
  picked as a victim for termination. A workaround is to                                                                      Resource use graphs allow people to understand
  include the number of rollbacks when selecting a                                                                            dependencies. According to Tanenbaum, research in
  process to rollback.                                                                                                        graph theory also keeps otherwise unemployed graph
                                                                                                                              theorists off the streets.
                                                     CP2002    Deadlocks [8]     Recovery from Deadlock [8.7] – p.101/102                                                                           CP2002      Deadlocks [8]   Summary – p.102/102

				
DOCUMENT INFO
Shared By:
Categories:
Stats:
views:20
posted:4/1/2010
language:English
pages:17
Description: 6pp - CP2002 Quick Review Quick Review Binary Semaphore Binary ...