Deadlocks, four necessary conditions for deadlock and treatment strategies

First, what is the deadlock
two, deadlock and starvation
three types of resources
  3.1 reusable resources and wasting resources
    3.1.1 reusable resources (permanent resources)
    3.1.2 wasting resources (temporary resources)
  3.2 Preemptible resources and can not seize resources
    3.2.1 can seize resources
    3.2.2 can not be preempted resources
four reasons deadlock
  4.1 competition can not seize resources lead to deadlock
  4.2 competition can consume resources lead to deadlock
  4.3 process forward deadlock caused by improper order
V. four necessary conditions for deadlock of
  5.1 mutually exclusive conditions:
  5.2 inalienable condition:
  5.3 request and keeping conditions:
  5.4 circular wait condition:
six methods of handling deadlock
  6.1 deadlock prevention
  6.2 avoid deadlock
    6.2.1 common avoid dead lock method
      6.2.1.1 ordered resource allocation method
      6.2.1.2 bankers algorithm
    6.2.2 used to avoid deadlock in the art
      6.2.2.1 locking sequence
      6.2.2.2 lock time
      6.2.2.3 deadlock detection
  6.3 detect deadlocks
  6.4 released deadlock
First, what is deadlock
Multi-threaded and multi-process improves the utilization of system resources and improves the processing capability of the system. However, concurrent execution has also brought new problems - the deadlock.
Deadlock refers to a deadlock between two or more processes (threads) during operation due to competition for resources caused by (Deadly-Embrace)), the absence of external force, these processes (threads) will not forward advance.

Let us illustrate with some examples deadlock.

Look at the example of a life, but only two people dine with a pair of chopsticks, two people take turns to eat (also has two chopsticks to eat). At some time, he took a left chopsticks, a man took the right chopsticks, two individuals simultaneously occupy a resource, waiting for another resource, this time A finish and release it occupied chopsticks waiting B, empathy, also B a wait and release it after eating possession of chopsticks, thus caught in a cycle of death, who can not continue to eat. . .
A similar situation also exists in the computer system. For example, a computer system has only one input device and a printer, the process P1 occupies the input device, while requesting the use of printer, but this time the printer is being occupied by process P2, and P2 is not released before the printer, and a request to use is being used by the P1 input device. So that the two processes with each other endlessly wait any longer, we are unable to continue, this time the two processes deadlock state.

Some conclusions about the deadlock:

  • The number of processes involved in the deadlock is at least two
  • All the processes involved in the deadlock are waiting for resources
  • Processes involved in the deadlock has been occupied at least two resources
  • Deadlock process is a subset of the system in the current process of collection
  • Deadlock will waste a lot of system resources, and even cause the system to crash.

Second, deadlock and hunger
hunger (Starvation) means the process has been a lack of resources.

Deadlock and starvation are due to compete for resources due process. Hunger generally do not possess the resources, the process deadlock possession of certain resources.

Third, the type of resource
3.1 reusable resources and wasting resources
3.1.1 reusable resources (permanent resources)
can be used multiple times multiple processes, such as all hardware.

Only be assigned to a process to use, does not allow multiple processes to share.
When the use of reusable resources shall be in accordance with the requested resource, in this order using the resource release process.
System in each category reusable resource unit number is relatively fixed, the process during operation, can neither create nor delete.
3.1.2 wasting resources (temporary resource)
, also known as temporary resource, is run by the process during the dynamic creation and consumption.

  • Consumption of resources during process operation is constantly changing, sometimes to zero.
  • Process during operation, we can continue to create unit consumable resources, put them in a buffer of the resource class in order to increase the number of units of the resource class.
  • Process during operation, may request a number of resource elements may be consumable, their consumption for the process, they are no longer returned to the resource class.

Consumable resources are usually created by a producer process, consumed by a consumer process. The most typical consumable resource is used for interprocess message communication.

3.2 can not be seized to seize resources and resources
3.2.1 can seize the resources
can be preempted resource refers to a process in obtaining such resources, which can then be preempted by other processes or systems. For these resources is not cause deadlock.

CPU and main memory resources belong to preemption.

3.2.2 not seize resources
once the system allocates a resource to the process, you can not recover it by force can only be used after the release of their own in the process.

Tape drives, printers and other resources belonging to the non-preemptive.

Fourth, the reason for the deadlock

  • Competition can not seize resources lead to deadlock

  The conventional system has not seize resources, their number is insufficient to meet the needs of multiple processes running, it makes the process during operation, due to an impasse over resources, such as tape drives, printers, and so on. Only competition for resources, it may not be seized deadlock, competition for available resources is not cause to seize the deadlock.

  • Competition can consume resources lead to deadlock
  • Process forward deadlock caused by improper order

  Process during operation, request and order the release of resources properly, will also lead to a deadlock. For example, concurrent processes P1, P2, respectively, to keep the resources R1, R2, and the application process P1 resources R2, process P2 when applying for resource R1, both of which are occupied because the required resources blocked.
  Semaphores improper use can also cause deadlock. Among other processes are waiting for each other to send a message, the result will make between these processes can not continue to move forward. For example, process A process B send a message waiting, and waiting for the process B Process A message sent, the process can be seen as A and B are not competing for the same resources, but lead to a deadlock in wait for each other's resources.
4.1 competition can not seize resources lead to deadlock
as: cause a deadlock when a shared file
system has two processes P1 and P2, which are ready to write two papers F1 and F2. Both of which are all reusable resources and can not be preempted. If the process P1 at the same time open F1, F2 P2 process opens the file, when P1 want to open F2 F2 Closed due to be occupied and blocked, when P2 want to open 1:00 Closed due F1 is occupied and blocked, this time will be wireless wait any longer, the formation of a deadlock.

4.2 Competition can lead to deadlock consume resources
, such as: causing deadlock process communication
system has three processes P1, P2 and P3, m1, m2, m3 is 3 may consume resources. Process P1 on the one hand to generate a message m1, which will be sent to the P2, P3 receives a message from another aspect m3. In one aspect the process P2 generates a message m2, which is sent to P3, on the other hand the received message from P1 m1. Similarly, the process generates a message M3 P3 on the one hand, which is sent to P1, P2 receiving a message from another aspect m2.
If someone receives three processes have to send a message generated by itself sent a message, you can continue to run smoothly no deadlock, but if all three processes before receiving someone else's message is a message without generating wait forever down, resulting in a deadlock.

4.3 process forward deadlock caused by improper order

上图中,如果按曲线1的顺序推进,两个进程可顺利完成;如果按曲线2的顺序推进,两个进程可顺利完成;如果按曲线3的顺序推进,两个进程可顺利完成;如果按曲线4的顺序推进,两个进程将进入不安全区D中,此时P1保持了资源R1,P2保持了资源R2,系统处于不安全状态,如果继续向前推进,则可能产生死锁。

五、产生死锁的四个必要条件
5.1 互斥条件:
进程要求对所分配的资源(如打印机)进行排他性控制,即在一段时间内某资源仅为一个进程所占有。此时若有其他进程请求该资源,则请求进程只能等待。

5.2 不可剥夺条件:
进程所获得的资源在未使用完毕之前,不能被其他进程强行夺走,即只能由获得该资源的进程自己来释放(只能是主动释放)。

5.3 请求与保持条件:
进程已经保持了至少一个资源,但又提出了新的资源请求,而该资源已被其他进程占有,此时请求进程被阻塞,但对自己已获得的资源保持不放。

5.4 循环等待条件:
存在一种进程资源的循环等待链,链中每一个进程已获得的资源同时被 链中下一个进程所请求。即存在一个处于等待状态的进程集合{Pl, P2, …, pn},其中Pi等 待的资源被P(i+1)占有(i=0, 1, …, n-1),Pn等待的资源被P0占有,如图2-15所示。

直观上看,循环等待条件似乎和死锁的定义一样,其实不然。按死锁定义构成等待环所 要求的条件更严,它要求Pi等待的资源必须由P(i+1)来满足,而循环等待条件则无此限制。 例如,系统中有两台输出设备,P0占有一台,PK占有另一台,且K不属于集合{0, 1, …, n}。

Pn等待一台输出设备,它可以从P0获得,也可能从PK获得。因此,虽然Pn、P0和其他 一些进程形成了循环等待圈,但PK不在圈内,若PK释放了输出设备,则可打破循环等待, 如图2-16所示。因此循环等待只是死锁的必要条件。

 

资源分配图含圈而系统又不一定有死锁的原因是同类资源数大于1。但若系统中每类资 源都只有一个资源,则资源分配图含圈就变成了系统出现死锁的充分必要条件。

以上这四个条件是死锁的必要条件,只要系统发生死锁,这些条件必然成立,而只要上述条件之一不满足,就不会发生死锁。

产生死锁的一个例子:

/**
 * 一个简单的死锁类
 * 当DeadLock类的对象flag==1时(td1),先锁定o1,睡眠500毫秒
 * 而td1在睡眠的时候另一个flag==0的对象(td2)线程启动,先锁定o2,睡眠500毫秒
 * td1睡眠结束后需要锁定o2才能继续执行,而此时o2已被td2锁定;
 * td2睡眠结束后需要锁定o1才能继续执行,而此时o1已被td1锁定;
 * td1、td2相互等待,都需要得到对方锁定的资源才能继续执行,从而死锁。
 */
public class DeadLock implements Runnable {
    public int flag = 1;  
    //静态对象是类的所有对象共享的  
    private static Object o1 = new Object(), o2 = new Object();  
    @Override  
    public void run() {  
        System.out.println("flag=" + flag);  
        if (flag == 1) {  
            synchronized (o1) {  
                try {  
                    Thread.sleep(500);  
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
                synchronized (o2) {  
                    System.out.println("1");  
                }  
            }  
        }  
        if (flag == 0) {  
            synchronized (o2) {  
                try {  
                    Thread.sleep(500);  
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
                synchronized (o1) {  
                    System.out.println("0");  
                }  
            }  
        }  
    }  

    public static void main(String[] args) {
        DeadLock td1 = new DeadLock();
        DeadLock td2 = new DeadLock();
        td1.flag = 1;
        td2.flag = 0;
        //td1,td2都处于可执行状态,但JVM线程调度先执行哪个线程是不确定的。  
        //td2的run()可能在td1的run()之前运行  
        new Thread(td1).start();  
        new Thread(td2).start();
    }  
}  

 

六、处理死锁的方法

  • 预防死锁:通过设置某些限制条件,去破坏产生死锁的四个必要条件中的一个或几个条件,来防止死锁的发生。
  • 避免死锁:在资源的动态分配过程中,用某种方法去防止系统进入不安全状态,从而避免死锁的发生。
  • 检测死锁:允许系统在运行过程中发生死锁,但可设置检测机构及时检测死锁的发生,并采取适当措施加以清除。
  • 解除死锁:当检测出死锁后,便采取适当措施将进程从死锁状态中解脱出来。

6.1 预防死锁

  • 破坏“互斥”条件:

就是在系统里取消互斥。若资源不被一个进程独占使用,那么死锁是肯定不会发生的。但一般来说在所列的四个条件中,“互斥”条件是无法破坏的。因此,在死锁预防里主要是破坏其他几个必要条件,而不去涉及破坏“互斥”条件。

注意:互斥条件不能被破坏,否则会造成结果的不可再现性。

  • 破坏“占有并等待”条件:

  破坏“占有并等待”条件,就是在系统中不允许进程在已获得某种资源的情况下,申请其他资源。即要想出一个办法,阻止进程在持有资源的同时申请其他资源。
  方法一:创建进程时,要求它申请所需的全部资源,系统或满足其所有要求,或什么也不给它。这是所谓的 “ 一次性分配”方案。
  方法二:要求每个进程提出新的资源申请前,释放它所占有的资源。这样,一个进程在需要资源S时,须先把它先前占有的资源R释放掉,然后才能提出对S的申请,即使它可能很快又要用到资源R。

  • 破坏“不可抢占”条件:

  破坏“不可抢占”条件就是允许对资源实行抢夺。

  方法一:如果占有某些资源的一个进程进行进一步资源请求被拒绝,则该进程必须释放它最初占有的资源,如果有必要,可再次请求这些资源和另外的资源。
  方法二:如果一个进程请求当前被另一个进程占有的一个资源,则操作系统可以抢占另一个进程,要求它释放资源。只有在任意两个进程的优先级都不相同的条件下,方法二才能预防死锁。

  • 破坏“循环等待”条件:

  破坏“循环等待”条件的一种方法,是将系统中的所有资源统一编号,进程可在任何时刻提出资源申请,但所有申请必须按照资源的编号顺序(升序)提出。这样做就能保证系统不出现死锁。

6.2 避免死锁
理解了死锁的原因,尤其是产生死锁的四个必要条件,就可以最大可能地避免、预防和解除死锁。所以,在系统设计、进程调度等方面注意如何让这四个必要条件不成立,如何确定资源的合理分配算法,避免进程永久占据系统资源。此外,也要防止进程在处于等待状态的情况下占用资源。因此,对资源的分配要给予合理的规划。

预防死锁和避免死锁的区别:
预防死锁是设法至少破坏产生死锁的四个必要条件之一,严格的防止死锁的出现,而避免死锁则不那么严格的限制产生死锁的必要条件的存在,因为即使死锁的必要条件存在,也不一定发生死锁。避免死锁是在系统运行过程中注意避免死锁的最终发生。

6.2.1 常用避免死锁的方法
6.2.1.1 有序资源分配法
这种算法资源按某种规则系统中的所有资源统一编号(例如打印机为1、磁带机为2、磁盘为3、等等),申请时必须以上升的次序。系统要求申请进程:
  1、对它所必须使用的而且属于同一类的所有资源,必须一次申请完;
  2、在申请不同类资源时,必须按各类设备的编号依次申请。例如:进程PA,使用资源的顺序是R1,R2; 进程PB,使用资源的顺序是R2,R1;若采用动态分配有可能形成环路条件,造成死锁。
  采用有序资源分配法:R1的编号为1,R2的编号为2;
  PA:申请次序应是:R1,R2
  PB:申请次序应是:R1,R2
  这样就破坏了环路条件,避免了死锁的发生。
  

6.2.1.2 银行家算法
详见银行家算法.

6.2.2 常用避免死锁的技术

  • 加锁顺序(线程按照一定的顺序加锁)
  • 加锁时限(线程尝试获取锁的时候加上一定的时限,超过时限则放弃对该锁的请求,并释放自己占有的锁)
  • 死锁检测

6.2.2.1 加锁顺序
当多个线程需要相同的一些锁,但是按照不同的顺序加锁,死锁就很容易发生。

如果能确保所有的线程都是按照相同的顺序获得锁,那么死锁就不会发生。看下面这个例子:

Thread 1: 
lock A 
lock B 
Thread 2: 
wait for A 
lock C (when A locked) 
Thread 3: 
wait for A 
wait for B 
wait for C

如果一个线程(比如线程3)需要一些锁,那么它必须按照确定的顺序获取锁。它只有获得了从顺序上排在前面的锁之后,才能获取后面的锁。

例如,线程2和线程3只有在获取了锁A之后才能尝试获取锁C(译者注:获取锁A是获取锁C的必要条件)。因为线程1已经拥有了锁A,所以线程2和3需要一直等到锁A被释放。然后在它们尝试对B或C加锁之前,必须成功地对A加了锁。

按照顺序加锁是一种有效的死锁预防机制。但是,这种方式需要你事先知道所有可能会用到的锁(译者注:并对这些锁做适当的排序),但总有些时候是无法预知的。

6.2.2.2 加锁时限
另外一个可以避免死锁的方法是在尝试获取锁的时候加一个超时时间,这也就意味着在尝试获取锁的过程中若超过了这个时限该线程则放弃对该锁请求。若一个线程没有在给定的时限内成功获得所有需要的锁,则会进行回退并释放所有已经获得的锁,然后等待一段随机的时间再重试。这段随机的等待时间让其它线程有机会尝试获取相同的这些锁,并且让该应用在没有获得锁的时候可以继续运行(译者注:加锁超时后可以先继续运行干点其它事情,再回头来重复之前加锁的逻辑)。

以下是一个例子,展示了两个线程以不同的顺序尝试获取相同的两个锁,在发生超时后回退并重试的场景:

Thread 1 locks A 
Thread 2 locks B 
Thread 1 attempts to lock B but is blocked 
Thread 2 attempts to lock A but is blocked 
Thread 1’s lock attempt on B times out 
Thread 1 backs up and releases A as well 
Thread 1 waits randomly (e.g. 257 millis) before retrying. 
Thread 2’s lock attempt on A times out 
Thread 2 backs up and releases B as well 
Thread 2 waits randomly (e.g. 43 millis) before retrying.

在上面的例子中,线程2比线程1早200毫秒进行重试加锁,因此它可以先成功地获取到两个锁。这时,线程1尝试获取锁A并且处于等待状态。当线程2结束时,线程1也可以顺利的获得这两个锁(除非线程2或者其它线程在线程1成功获得两个锁之前又获得其中的一些锁)。

需要注意的是,由于存在锁的超时,所以我们不能认为这种场景就一定是出现了死锁。也可能是因为获得了锁的线程(导致其它线程超时)需要很长的时间去完成它的任务。

此外,如果有非常多的线程同一时间去竞争同一批资源,就算有超时和回退机制,还是可能会导致这些线程重复地尝试但却始终得不到锁。如果只有两个线程,并且重试的超时时间设定为0到500毫秒之间,这种现象可能不会发生,但是如果是10个或20个线程情况就不同了。因为这些线程等待相等的重试时间的概率就高的多(或者非常接近以至于会出现问题)。
(译者注:超时和重试机制是为了避免在同一时间出现的竞争,但是当线程很多时,其中两个或多个线程的超时时间一样或者接近的可能性就会很大,因此就算出现竞争而导致超时后,由于超时时间一样,它们又会同时开始重试,导致新一轮的竞争,带来了新的问题。)

这种机制存在一个问题,在Java中不能对synchronized同步块设置超时时间。你需要创建一个自定义锁,或使用Java5中java.util.concurrent包下的工具。写一个自定义锁类不复杂,但超出了本文的内容。后续的Java并发系列会涵盖自定义锁的内容。

6.2.2.3 死锁检测
死锁检测是一个更好的死锁预防机制,它主要是针对那些不可能实现按序加锁并且锁超时也不可行的场景。

每当一个线程获得了锁,会在线程和锁相关的数据结构中(map、graph等等)将其记下。除此之外,每当有线程请求锁,也需要记录在这个数据结构中。

当一个线程请求锁失败时,这个线程可以遍历锁的关系图看看是否有死锁发生。例如,线程A请求锁7,但是锁7这个时候被线程B持有,这时线程A就可以检查一下线程B是否已经请求了线程A当前所持有的锁。如果线程B确实有这样的请求,那么就是发生了死锁(线程A拥有锁1,请求锁7;线程B拥有锁7,请求锁1)。

当然,死锁一般要比两个线程互相持有对方的锁这种情况要复杂的多。线程A等待线程B,线程B等待线程C,线程C等待线程D,线程D又在等待线程A。线程A为了检测死锁,它需要递进地检测所有被B请求的锁。从线程B所请求的锁开始,线程A找到了线程C,然后又找到了线程D,发现线程D请求的锁被线程A自己持有着。这是它就知道发生了死锁。

下面是一幅关于四个线程(A,B,C和D)之间锁占有和请求的关系图。像这样的数据结构就可以被用来检测死锁。

 

6.3 检测死锁
一般来说,由于操作系统有并发,共享以及随机性等特点,通过预防和避免的手段达到排除死锁的目的是很困难的。这需要较大的系统开销,而且不能充分利用资源。为此,一种简便的方法是系统为进程分配资源时,不采取任何限制性措施,但是提供了检测和解脱死锁的手段:能发现死锁并从死锁状态中恢复出来。因此,在实际的操作系统中往往采用死锁的检测与恢复方法来排除死锁。
死锁检测与恢复是指系统设有专门的机构,当死锁发生时,该机构能够检测到死锁发生的位置和原因,并能通过外力破坏死锁发生的必要条件,从而使得并发进程从死锁状态中恢复出来。
这时进程P1占有资源R1而申请资源R2,进程P2占有资源R2而申请资源R1,按循环等待条件,进程和资源形成了环路,所以系统是死锁状态。进程P1,P2是参与死锁的进程。
下面我们再来看一看死锁检测算法。算法使用的数据结构是如下这些:
占有矩阵A:n*m阶,其中n表示并发进程的个数,m表示系统的各类资源的个数,这个矩阵记录了每一个进程当前占有各个资源类中资源的个数。
申请矩阵R:n*m阶,其中n表示并发进程的个数,m表示系统的各类资源的个数,这个矩阵记录了每一个进程当前要完成工作需要申请的各个资源类中资源的个数。
空闲向量T:记录当前m个资源类中空闲资源的个数。
完成向量F:布尔型向量值为真(true)或假(false),记录当前n个并发进程能否进行完。为真即能进行完,为假则不能进行完。
临时向量W:开始时W:=T。
算法步骤:
(1)W:=T,
对于所有的i=1,2,…,n,
如果A[i]=0,则F[i]:=true;否则,F[i]:=false
(2)找满足下面条件的下标i:
F[i]:=false并且R[i]〈=W
如果不存在满足上面的条件i,则转到步骤(4)。
(3)W:=W+A[i]
F[i]:=true
转到步骤(2)
(4)如果存在i,F[i]:=false,则系统处于死锁状态,且Pi进程参与了死锁。什么时候进行死锁的检测取决于死锁发生的频率。如果死锁发生的频率高,那么死锁检测的频率也要相应提高,这样一方面可以提高系统资源的利用率,一方面可以避免更多的进程卷入死锁。如果进程申请资源不能满足就立刻进行检测,那么每当死锁形成时即能被发现,这和死锁避免的算法相近,只是系统的开销较大。为了减小死锁检测带来的系统开销,一般采取每隔一段时间进行一次死锁检测,或者在CPU的利用率降低到某一数值时,进行死锁的检测。

6.4 解除死锁
一旦检测出死锁,就应立即釆取相应的措施,以解除死锁。
死锁解除的主要方法有:
1) 资源剥夺法。挂起某些死锁进程,并抢占它的资源,将这些资源分配给其他的死锁进程。但应防止被挂起的进程长时间得不到资源,而处于资源匮乏的状态。
2) 撤销进程法。强制撤销部分、甚至全部死锁进程并剥夺这些进程的资源。撤销的原则可以按进程优先级和撤销进程代价的高低进行。
3) 进程回退法。让一(多)个进程回退到足以回避死锁的地步,进程回退时自愿释放资源而不是被剥夺。要求系统保持进程的历史信息,设置还原点。

 

原文链接:https://blog.csdn.net/wljliujuan/article/details/79614019

Guess you like

Origin www.cnblogs.com/ldcs/p/12001896.html