Deadlock and prevention strategies

What is a deadlock?

  • If each process a process set can only have only one other incident to the collection process initiated in waiting, this situation is a deadlock.

  • Simple example

    • Resource A and resource B are inalienable resources

    • C process has already applied to the resource A, D process has already applied to the resource B

    • At this time, the application process C resources B, D and process just applied for a resource A

    • Because resources have been occupied, processes A and B can not be the next step, causing a deadlock.

      image-20191109150926746

Generates four necessary conditions for deadlock

  • Mutually exclusive conditions (Mutual exclusive)
    • Resources can not be shared, can only be used by a process.
  • Request holding condition (Hold and Wait)
    • It has been resource processes can apply for a new resource again.
  • Non-deprivation (No pre-emption)
    • Resources have been allocated can not be forcibly deprived from the corresponding process.
  • Loop wait condition (Circular wait)
    • System consisting of a number of process loop, the loop every process is waiting for resources adjacent to occupy the whole process.

Deadlock Strategy

  • Deadlock prevention

    • Some provided one or several four conditions necessary condition in deadlock damage, to prevent deadlock.
  • Avoid deadlock

    • In dynamic allocation of resources in some way prevent the system from entering a state of insecurity, in order to avoid deadlock.
  • Deadlock detection and de

    • Need to take any restrictive measures, allows a process to a deadlock occurs during operation. Detecting the occurrence of deadlock detection mechanism in a timely manner through the system, and then to take some measures to relieve the deadlock.
    Resource allocation policy Various possible modes The main advantage The main drawback
    Deadlock Prevention Conservative, rather resource constraints Once all requested resources, resource deprivation, sequential allocation of resources Do apply to the processing of the burst process, you do not have to be deprived. Low efficiency, prolonged process initialization; too often deprived; inconvenience flexible application of new resources.
    Deadlock Avoidance "Prevention" and "detection" of compromise Order to allow for possible security You do not have to deprive We must know the future resource needs; the process can not be blocked for a long time.
    Deadlock Detection Loose, as long as it is allowed to allocate resources Regularly check whether a deadlock has occurred It does not extend the process initialization time, allowing the deadlock on-site treatment. Loss deadlock caused by depriving lifted.
  • Banker's algorithm:

    • The operating system is seen as a banker, operating system management of resources equivalent to bankers managing the funds, the process of requesting the allocation of resources to the operating system the user is equivalent to the bankers loans.
    • The operating system allocates resources for the process according to the rules established by the bankers, when the process first application resources, to test the process maximum demand for resources, if the system existing resources to meet its current maximum demand for press distribution applications resources, or to defer the distribution.
    • When the process continue to apply resources in the implementation, to test the process and the number of occupied resources of this application and the number of resources exceeds the maximum demand on the resources of the process.
    • If more than the refusal to allocate resources, had no more than the existing system and then test whether the resources still need the maximum amount of resources to meet the process, if we meet the current allocation of resources according to the applicant, otherwise it should be postponed.
  • Methods to relieve deadlock

    • Resources deprive law: suspend certain death process and snatch its resources, so that other processes continue to advance
    • Revocation process of law: mandatory revocation of part or all of the process deadlock resources and deprive these processes
    • Process fallback method: let the process falls back to the point where enough to avoid deadlock

Example Problems

  • Leetcode 1226 title, the Dining Philosophers

  • 5 taciturn philosophers sitting around the round table, in front of a pasta per person. Fork on the table between philosophers. (5 philosopher fork 5)

    All philosophers will alternate between thinking and eating two acts. Only a philosopher at the same time to get a fork to eat the left and right side, with a fork and a philosopher can only be used in the same time. Each philosopher needs to after eating face fork back into the desktop for other philosophers noodles. As long as conditions permit, the philosopher can pick up a fork to the left or the right, but can not eat at the same time not get around a fork.

    Assuming that the number of face no restrictions, philosophers can not just eat, eat no need to consider not endure.

    Design a meal rule (parallel algorithm) so that each philosopher will not starve; that is, when no one knows what to think or what other people when you want to eat, each philosopher can think of eating and He has been alternating between down.

    img

  • Philosophers from 0-4 clockwise numbered. Please realize the function void wantsToEat (philosopher, pickLeftFork, pickRightFork, eat, putLeftFork, putRightFork):

    • philosopher Philosophers number.
    • pickLeftForkAnd pickRightForkrepresents pick up a fork to the left or right.
    • eat Expressed noodles.
    • putLeftForkAnd pickRightForkrepresents a fork down the left or right.
    • As the philosopher is not in the noodles was thinking Shashi Hou eat noodles, so think about this method does not correspond to the callback.
  • Give you five threads, each representing a philosopher, you use the same object class to simulate this process.

  • Before the end of the last call, as the same may be several times the function is called a philosopher.

  • Example:

    输入:n = 1
    输出:[[4,2,1],[4,1,1],[0,1,1],[2,2,1],[2,1,1],[2,0,3],[2,1,2],[2,2,2],[4,0,3],[4,1,2],[0,2,1],[4,2,2],[3,2,1],[3,1,1],[0,0,3],[0,1,2],[0,2,2],[1,2,1],[1,1,1],[3,0,3],[3,1,2],[3,2,2],[1,0,3],[1,1,2],[1,2,2]]
    解释:
    n 表示每个哲学家需要进餐的次数。
    输出数组描述了叉子的控制和进餐的调用,它的格式如下:
    output[i] = [a, b, c] (3个整数)
    - a 哲学家编号。
    - b 指定叉子:{1 : 左边, 2 : 右边}.
    - c 指定行为:{1 : 拿起, 2 : 放下, 3 : 吃面}。
    如 [4,2,1] 表示 4 号哲学家拿起了右边的叉子。 
    • A Solution

      package com.ronnie.leetcode;
      
      import java.util.concurrent.Semaphore;
      import java.util.concurrent.locks.ReentrantLock;
      
      public class DiningPhilosophers {
      
          // 1 fork => 1 ReetrantLock
          private ReentrantLock[] lockList = {
                  new ReentrantLock(),
                  new ReentrantLock(),
                  new ReentrantLock(),
                  new ReentrantLock(),
                  new ReentrantLock()
          };
          // restriction: Only 4 Philosophers can get at least one fork
          private Semaphore eatLimit = new Semaphore(4);
      
          public DiningPhilosophers() {
      
          }
      
          // call the run() method of any runnable to execute its code
          public void wantsToEat(int philosopher,
                                 Runnable pickLeftFork,
                                 Runnable pickRightFork,
                                 Runnable eat,
                                 Runnable putLeftFork,
                                 Runnable putRightFork) throws InterruptedException {
      
              int leftFork = (philosopher+1)%5;
              int rightFork = philosopher;
              eatLimit.acquire();
      
              lockList[leftFork].lock();
              lockList[rightFork].lock();
      
              pickLeftFork.run();
              pickRightFork.run();
      
              eat.run();
      
              putLeftFork.run();
              putRightFork.run();
      
              lockList[leftFork].unlock();
              lockList[rightFork].unlock();
      
              eatLimit.release();
          }
      }
    • Solution two

      package com.ronnie.leetcode;
      
      import java.util.concurrent.locks.ReentrantLock;
      
      public class DiningPhilosophers2 {
      
          // 1 fork => 1 ReentrantLock
          private ReentrantLock[] lockList = {
                new ReentrantLock(),
                new ReentrantLock(),
                new ReentrantLock(),
                new ReentrantLock()
          };
      
          // 思路: 设置一个临界区, 进入临界区后, 只有当哲学家获取到左右两把叉子并执行代码后, 才退出临界区
          private ReentrantLock pickBothForks = new ReentrantLock();
      
          public DiningPhilosophers2(){
      
          }
      
      
          // call the run() method of any runnable to execute its code
          public void wantsToEat(int philosopher,
                                 Runnable pickLeftFork,
                                 Runnable pickRightFork,
                                 Runnable eat,
                                 Runnable putLeftFork,
                                 Runnable putRightFork) throws InterruptedException {
      
                      int leftFork = (philosopher + 1) % 5;
                      int rightFork = philosopher;
      
                      // 进入临界区
                      lockList[leftFork].lock();
                      lockList[rightFork].lock();
      
                      pickLeftFork.run();
                      pickRightFork.run();
      
                      // 退出临界区
                      pickBothForks.unlock();
      
                      putLeftFork.run();
                      pickRightFork.run();
      
                      lockList[leftFork].unlock();
                      lockList[rightFork].unlock();
          }
      }
    • Solution three

      package com.ronnie.leetcode;
      
      import java.util.concurrent.locks.ReentrantLock;
      
      /**
       *  只有当5个哲学家都左手持其左边的叉子 或 都右手持有期右边的叉子时, 才会发送死锁。
       */
      public class DiningPhilosophers3 {
          // 1 fork => 1 ReetrantLock
          private ReentrantLock[] lockList = {
                  new ReentrantLock(),
                  new ReentrantLock(),
                  new ReentrantLock(),
                  new ReentrantLock(),
                  new ReentrantLock()
          };
      
          public DiningPhilosophers3() {
          }
      
          // call the run() method of any runnable to execute its code
          public void wantsToEat(int philosopher,
                                 Runnable pickLeftFork,
                                 Runnable pickRightFork,
                                 Runnable eat,
                                 Runnable putLeftFork,
                                 Runnable putRightFork) throws InterruptedException {
              int leftFork = (philosopher + 1) % 5;
              int rightFork = philosopher;
      
              // 让编号为偶数的哲学家优先拿左边, 再拿右边
              if (philosopher % 2 == 0){
                  lockList[leftFork].lock();
                  lockList[rightFork].lock();
              } else {
                  // 编号为奇数的旧先拿右边再拿左边, 这样就避免了死锁
                  lockList[rightFork].lock();
                  lockList[leftFork].lock();
              }
      
              pickLeftFork.run();
              pickRightFork.run();
      
              eat.run();
      
              putLeftFork.run();
              putRightFork.run();
      
              lockList[leftFork].unlock();
              lockList[rightFork].unlock();
          }
      }
      

Guess you like

Origin www.cnblogs.com/ronnieyuan/p/11828316.html