CH6-Deadlock

死锁(Deadlocks)概述


1. 资源(Resources)

资源的定义:
Definition of Resources:
• 资源是任何可以在某一时刻被单个进程使用,并且必须经过获取、使用和释放的过程。
A resource is anything that can be used by a single process at any instant of time and must be acquired, used, and released over time.

资源类型:
Resource Types:
• 资源类型包括CPU周期、内存空间、I/O设备、数据库记录等。
Resource types include CPU cycles, memory space, I/O devices, database records, etc.
• 每种资源类型 \(R_i\)\(W_i\) 个实例。
Each resource type \(R_i\) has \(W_i\) instances.

资源的分类:
Classification of Resources:
1. 可抢占资源(Preemptable Resources):
◦ 可以从进程中强制收回而不会对进程造成影响。
Can be taken away from a process without ill effects.
◦ 示例:CPU、内存。
Examples: CPU, memory.
2. 不可抢占资源(Nonpreemptable Resources):
◦ 如果被强制收回,会导致进程失败。
If taken away, it will cause the process to fail.
◦ 示例:CD刻录机、打印机。
Examples: CD recorder, printer.


2. 死锁的定义(Introduction to Deadlocks)

死锁的发生条件:
Conditions for Deadlocks:
• 进程需要以合理的顺序访问资源。
Processes need to access resources in a reasonable order.
• 如果一个进程持有资源 \(A\) 并请求资源 \(B\),而另一个进程持有资源 \(B\) 并请求资源 \(A\),则两个进程都会被阻塞。
If one process holds resource A and requests resource B, while another process holds resource B and requests resource A, both processes will be blocked.
• 当进程被授予对设备的独占访问权时,死锁可能发生。
Deadlocks occur when processes are granted exclusive access to devices.


3. 死锁的资源使用过程

资源的使用步骤:
Steps in Resource Usage:
1. 请求资源(Request the Resource):
◦ 进程请求资源以执行任务。
The process requests a resource to perform a task.
2. 使用资源(Use the Resource):
◦ 进程占用资源并执行任务。
The process uses the resource to perform the task.
3. 释放资源(Release the Resource):
◦ 进程完成任务后释放资源。
The process releases the resource after completing the task.

请求被拒绝的情况:
When a Request is Denied:
• 请求资源的进程可能会被阻塞。
The requesting process may be blocked.
• 进程可能会因错误代码而失败。
The process may fail with an error code.


4. 死锁的示例

死锁的场景:
Deadlock Scenario:
• 假设有两个进程 \(P_1\)\(P_2\)
Suppose there are two processes \(P_1\) and \(P_2\):
1. \(P_1\) 持有资源 \(A\)(例如扫描仪),并请求资源 \(B\)(例如CD刻录机)。
\(P_1\) holds resource A (e.g., scanner) and requests resource B (e.g., CD recorder).
2. \(P_2\) 持有资源 \(B\)(CD刻录机),并请求资源 \(A\)(扫描仪)。
\(P_2\) holds resource B (CD recorder) and requests resource A (scanner).
3. 两个进程都被阻塞,并且一直保持阻塞状态。
Both processes are blocked and remain so.

死锁的条件(死锁的四个必要条件):
Conditions for Deadlocks (Four Necessary Conditions):
1. 互斥条件(Mutual Exclusion):
◦ 资源一次只能被一个进程占用。
A resource can be held by only one process at a time.
2. 占有并等待(Hold and Wait):
◦ 进程持有至少一个资源,并等待获取其他被占用的资源。
A process holds at least one resource and is waiting to acquire other resources that are currently held.
3. 不可抢占(No Preemption):
◦ 资源不能被强制从进程中收回,只能由进程主动释放。
Resources cannot be forcibly taken away from a process; they must be released voluntarily.
4. 循环等待(Circular Wait):
◦ 存在一个进程环,每个进程都在等待环中的下一个进程持有的资源。
There exists a circular chain of processes, where each process is waiting for a resource held by the next process in the chain.


5. 死锁的处理方法

5.1 鸵鸟算法(The Ostrich Algorithm)

定义:
Definition:
• 忽略死锁问题,假设死锁不会发生或发生的概率极低。
Ignore the deadlock problem, assuming that deadlocks either do not occur or occur with very low probability.优点:
Advantages:
• 简单易实现。
Simple and easy to implement.
缺点:
Disadvantages:
• 不适用于需要高可靠性的系统。
Not suitable for systems requiring high reliability.


5.2 死锁检测与恢复(Deadlock Detection and Recovery)

检测:
Detection:
• 使用资源分配图或其他算法检测系统中是否存在死锁。
Use resource allocation graphs or other algorithms to detect deadlocks in the system.恢复:
Recovery:
• 通过终止某些进程或强制回收资源来解除死锁。
Terminate some processes or forcibly reclaim resources to resolve the deadlock.


5.3 死锁避免(Deadlock Avoidance)

定义:
Definition:
• 在分配资源之前,系统会预测是否会导致死锁,从而避免进入不安全状态。
Before allocating resources, the system predicts whether a deadlock will occur, thereby avoiding unsafe states.算法:
Algorithms:
银行家算法(Banker's Algorithm):
◦ 通过模拟资源分配过程,确保系统始终处于安全状态。
Simulates resource allocation to ensure the system remains in a safe state.


5.4 死锁预防(Deadlock Prevention)

定义:
Definition:
• 通过破坏死锁的四个必要条件之一来预防死锁的发生。
Prevent deadlocks by breaking one of the four necessary conditions for deadlocks.方法:
Methods:
1. 破坏互斥条件:
◦ 允许多个进程共享某些资源(如只读文件)。
Allow multiple processes to share certain resources (e.g., read-only files).
2. 破坏占有并等待:
◦ 要求进程在请求资源时一次性申请所有需要的资源。
Require processes to request all needed resources at once.
3. 破坏不可抢占:
◦ 允许强制回收资源(仅适用于可抢占资源)。
Allow forced reclamation of resources (only applicable to preemptable resources).
4. 破坏循环等待:
◦ 对资源进行编号,要求进程按编号顺序请求资源。
Number resources and require processes to request them in order.


6. 其他问题(Other Issues)

死锁与饥饿的区别:
Difference Between Deadlock and Starvation:
死锁: 所有相关进程都被永久阻塞。
Deadlock: All involved processes are permanently blocked.
饥饿: 某些进程可能长期得不到资源,但并非所有进程都被阻塞。
Starvation: Some processes may be denied resources for a long time, but not all processes are blocked.

资源分配策略:
Resource Allocation Policies:
• 公平分配资源,避免某些进程长期占用资源。
Fairly allocate resources to avoid long-term resource occupation by certain processes.


总结

死锁是操作系统中常见的问题,发生时会导致系统性能下降甚至完全不可用。
Deadlocks are a common problem in operating systems, causing performance degradation or complete system unavailability when they occur.

死锁的四个必要条件:互斥、占有并等待、不可抢占、循环等待。
The four necessary conditions for deadlocks are mutual exclusion, hold and wait, no preemption, and circular wait.

处理死锁的方法包括:忽略(鸵鸟算法)、检测与恢复、避免(银行家算法)、预防(破坏死锁条件)。
Deadlock handling methods include ignoring (ostrich algorithm), detection and recovery, avoidance (Banker's Algorithm), and prevention (breaking deadlock conditions).

死锁预防和避免是操作系统中重要的资源管理策略,能够有效提高系统的可靠性和性能。
Deadlock prevention and avoidance are important resource management strategies in operating systems, significantly improving system reliability and performance.


死锁的深入分析

1. 使用信号量共享资源(Using Semaphore to Share Resource)

信号量的作用:
Role of Semaphores:
• 信号量用于控制对共享资源的访问,确保同一时间只有一个进程可以访问资源。
Semaphores are used to control access to shared resources, ensuring that only one process can access a resource at a time.

示例:两个进程共享两个资源(A和B)
Example: Two Processes Sharing Two Resources (A and B)

代码示例 1:正常情况
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Process P() {
A.Down(); // 请求资源A
B.Down(); // 请求资源B
// 使用资源A和B
B.Up(); // 释放资源B
A.Up(); // 释放资源A
}

Process Q() {
A.Down(); // 请求资源A
B.Down(); // 请求资源B
// 使用资源A和B
B.Up(); // 释放资源B
A.Up(); // 释放资源A
}

信号量初始化:
• 如果信号量 \(A(1), B(1)\),表示资源A和B初始可用。
If semaphore \(A(1), B(1)\), resources A and B are initially available.

问题:
• 如果两个进程同时请求资源A和B,可能会导致死锁。
If two processes request resources A and B simultaneously, a deadlock may occur.


代码示例 2:可能导致死锁的情况
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Process P() {
A.Down(); // 请求资源A
B.Down(); // 请求资源B
// 使用资源A和B
B.Up(); // 释放资源B
A.Up(); // 释放资源A
}

Process Q() {
B.Down(); // 请求资源B
A.Down(); // 请求资源A
// 使用资源A和B
A.Up(); // 释放资源A
B.Up(); // 释放资源B
}

信号量初始化:
• 如果信号量 \(A(1), B(1)\),两个进程可能会进入死锁状态:
If semaphore \(A(1), B(1)\), the two processes may enter a deadlock state:
1. \(P\) 请求 \(A\)\(Q\) 请求 \(B\)
\(P\) requests \(A\), \(Q\) requests \(B\).
2. \(P\) 等待 \(B\)\(Q\) 等待 \(A\)
\(P\) waits for \(B\), \(Q\) waits for \(A\).
3. 两个进程互相等待,导致死锁。
Both processes wait for each other, causing a deadlock.


2. 死锁的实际案例:桥的交叉问题(Bridge Crossing Example)

场景描述:
Scenario Description:
• 桥上的交通只能单向行驶。
Traffic on the bridge can only travel in one direction.
• 桥的每个部分可以被视为一个资源。
Each section of the bridge can be viewed as a resource.
• 如果两辆车从桥的相反方向进入,可能会导致死锁。
If two cars enter the bridge from opposite sides, a deadlock may occur.

死锁的解决方法:
Deadlock Resolution:
• 如果发生死锁,其中一辆车需要倒车(抢占资源并回滚)。
If a deadlock occurs, one car needs to back up (preempt resources and roll back).
• 如果多辆车同时进入桥,可能需要多辆车倒车。
If multiple cars enter the bridge simultaneously, multiple cars may need to back up.


3. 死锁的正式定义(Formal Definition of Deadlock)

定义:
Definition:
• 如果一组进程中的每个进程都在等待一个事件,而该事件只能由该组中的另一个进程引发,则这组进程处于死锁状态。
A set of processes is deadlocked if each process in the set is waiting for an event that only another process in the set can cause.

通常的事件:
Typical Event:
• 资源的释放。
Release of a currently held resource.

死锁的表现:
Manifestations of Deadlock:
• 进程无法运行。
Processes cannot run.
• 进程无法释放资源。
Processes cannot release resources.
• 进程无法被唤醒。
Processes cannot be awakened.


4. 死锁的四个必要条件(Four Conditions for Deadlock)

条件 1:互斥条件(Mutual Exclusion Condition)
• 每个资源一次只能分配给一个进程,或者处于可用状态。
Each resource is assigned to one process or is available.

条件 2:占有并等待条件(Hold and Wait Condition)
• 持有资源的进程可以请求额外的资源。
A process holding resources can request additional resources.

条件 3:不可抢占条件(No Preemption Condition)
• 已分配的资源不能被强制收回,必须由持有进程显式释放。
Previously granted resources cannot be forcibly taken away; they must be explicitly released by the holding process.

条件 4:循环等待条件(Circular Wait Condition)
• 必须存在一个由两个或更多进程组成的循环链,每个进程都在等待下一个进程持有的资源。
There must be a circular chain of two or more processes, where each is waiting for a resource held by the next member of the chain.

死锁的发生:
• 如果上述四个条件同时满足,则可能发生死锁。
Deadlock can arise if all four conditions are satisfied simultaneously.


5. 死锁的示例与分析

示例 1:正常情况

信号量初始化: \(A(1), B(1)\)
进程执行顺序:
1. \(P\) 请求 \(A\),成功。
2. \(P\) 请求 \(B\),成功。
3. \(P\) 释放 \(B\)\(A\)
4. \(Q\) 请求 \(A\),成功。
5. \(Q\) 请求 \(B\),成功。
6. \(Q\) 释放 \(B\)\(A\)

结果:
• 没有死锁,资源分配合理。
No deadlock, resources are allocated reasonably.


示例 2:死锁情况

信号量初始化: \(A(1), B(1)\)
进程执行顺序:
1. \(P\) 请求 \(A\),成功。
2. \(Q\) 请求 \(B\),成功。
3. \(P\) 请求 \(B\),被阻塞(因为 \(B\)\(Q\) 持有)。
4. \(Q\) 请求 \(A\),被阻塞(因为 \(A\)\(P\) 持有)。

结果:
• 死锁发生,两个进程互相等待。
Deadlock occurs, with both processes waiting for each other.


6. 死锁的解决方法

方法 1:死锁检测与恢复

检测:
• 使用资源分配图或其他算法检测系统中是否存在死锁。
Use resource allocation graphs or other algorithms to detect deadlocks in the system.恢复:
• 终止某些进程或强制回收资源以解除死锁。
Terminate some processes or forcibly reclaim resources to resolve the deadlock.


方法 2:死锁避免

银行家算法(Banker's Algorithm):
• 通过模拟资源分配过程,确保系统始终处于安全状态。
Simulate resource allocation to ensure the system remains in a safe state.


方法 3:死锁预防

破坏互斥条件:
• 允许多个进程共享某些资源(如只读文件)。
Allow multiple processes to share certain resources (e.g., read-only files).破坏占有并等待:
• 要求进程在请求资源时一次性申请所有需要的资源。
Require processes to request all needed resources at once.破坏不可抢占:
• 允许强制回收资源(仅适用于可抢占资源)。
Allow forced reclamation of resources (only applicable to preemptable resources).破坏循环等待:
• 对资源进行编号,要求进程按编号顺序请求资源。
Number resources and require processes to request them in order.


总结

死锁是操作系统中常见的问题,发生时会导致系统性能下降甚至完全不可用。
Deadlocks are a common problem in operating systems, causing performance degradation or complete system unavailability when they occur.

死锁的四个必要条件:互斥、占有并等待、不可抢占、循环等待。
The four necessary conditions for deadlocks are mutual exclusion, hold and wait, no preemption, and circular wait.

解决死锁的方法包括:检测与恢复、避免(银行家算法)、预防(破坏死锁条件)。
Deadlock handling methods include detection and recovery, avoidance (Banker's Algorithm), and prevention (breaking deadlock conditions).

信号量是控制资源共享的重要工具,但如果不正确使用,可能会导致死锁。
Semaphores are important tools for controlling resource sharing, but improper use can lead to deadlocks.


死锁建模(Deadlock Modeling)


1. 死锁建模的基本概念

死锁建模的方式:
Deadlock Modeling Approach:
• 使用有向图(Directed Graph)来表示系统中进程和资源之间的关系。
Use a directed graph to represent the relationships between processes and resources in a system.

图的组成:
Graph Components:
顶点集合 \(V\)
◦ 包含两类顶点:进程 \(P\) 和资源 \(R\)
Consists of two types of vertices: processes \(P\) and resources \(R\).
边集合 \(E\)
◦ 包含两种边:请求边(request edge)和分配边(assignment edge)。
Consists of two types of edges: request edges and assignment edges.


2. 资源分配图(Resource Allocation Graph, RAG)

定义:
Definition:
• 资源分配图是一个有向图,用于表示系统中进程和资源的关系。
A Resource Allocation Graph (RAG) is a directed graph that represents the relationships between processes and resources in a system.

顶点集合 \(V\)
Vertex Set \(V\):
\(V\) 被划分为两类:
\(V\) is partitioned into two types:
1. 进程集合 \(P\)
◦ 包含系统中所有进程 \(P_1, P_2, \dots, P_n\)
Contains all processes in the system: \(P_1, P_2, \dots, P_n\).
2. 资源集合 \(R\)
◦ 包含系统中所有资源类型 \(R_1, R_2, \dots, R_m\)
Contains all resource types in the system: \(R_1, R_2, \dots, R_m\).

边集合 \(E\)
Edge Set \(E\):
请求边(Request Edge):
◦ 表示进程 \(P_i\) 正在请求资源 \(R_j\)
Indicates that process \(P_i\) is requesting resource \(R_j\).
◦ 表示为:\(P_i \to R_j\)
Represented as: \(P_i \to R_j\).
分配边(Assignment Edge):
◦ 表示资源 \(R_j\) 已分配给进程 \(P_i\)
Indicates that resource \(R_j\) is assigned to process \(P_i\).
◦ 表示为:\(R_j \to P_i\)
Represented as: \(R_j \to P_i\).

img

3. 死锁的建模示例

示例场景:
Example Scenario:
• 进程 \(A\) 持有资源 \(R_1\),并请求资源 \(R_2\)
Process \(A\) holds resource \(R_1\) and requests resource \(R_2\).
• 进程 \(B\) 持有资源 \(R_2\),并请求资源 \(R_1\)
Process \(B\) holds resource \(R_2\) and requests resource \(R_1\).
• 进程 \(C\)\(D\) 在资源 \(T\)\(U\) 上发生死锁。
Processes \(C\) and \(D\) are deadlocked over resources \(T\) and \(U\).

资源分配图的表示:
Representation of the Resource Allocation Graph:
节点:
◦ 进程节点:\(A, B, C, D\)
◦ 资源节点:\(R_1, R_2, T, U\)
边:
\(A \to R_2\):进程 \(A\) 请求资源 \(R_2\)
\(R_1 \to A\):资源 \(R_1\) 分配给进程 \(A\)
\(B \to R_1\):进程 \(B\) 请求资源 \(R_1\)
\(R_2 \to B\):资源 \(R_2\) 分配给进程 \(B\)
\(C \to T, T \to D, D \to U, U \to C\):进程 \(C\)\(D\) 在资源 \(T\)\(U\) 上形成循环等待,导致死锁。


4. 死锁的发生条件

无环图:
Acyclic Graph:
• 如果资源分配图中没有环,则系统中不存在死锁。
If the resource allocation graph contains no cycles, there is no deadlock in the system.

有环图:
Cyclic Graph:
• 如果资源分配图中存在环,则可能存在死锁。
If the resource allocation graph contains cycles, deadlock may occur.
单资源实例:
◦ 如果每个资源类型只有一个实例,则图中存在环意味着一定存在死锁。
If there is only one instance per resource type, a cycle in the graph guarantees a deadlock.
多资源实例:
◦ 如果每个资源类型有多个实例,则图中存在环仅表示可能存在死锁。
If there are multiple instances per resource type, a cycle in the graph indicates the possibility of deadlock.


5. 死锁建模的示例分析

示例 1:无死锁的资源分配图

资源分配图:
• 进程 \(P_1\) 持有资源 \(R_1\)
• 进程 \(P_2\) 持有资源 \(R_2\)
• 进程 \(P_1\) 请求资源 \(R_2\)
• 进程 \(P_2\) 请求资源 \(R_1\)
But no deadlock occurs because the processes are not yet holding the requested resources.

图表示:
\(P_1 \to R_2\):进程 \(P_1\) 请求资源 \(R_2\)
\(P_2 \to R_1\):进程 \(P_2\) 请求资源 \(R_1\)
\(R_1 \to P_2\):资源 \(R_1\) 分配给进程 \(P_2\)
\(R_2 \to P_1\):资源 \(R_2\) 分配给进程 \(P_1\)
No cycle exists, so no deadlock.


示例 2:有死锁的资源分配图

资源分配图:
• 进程 \(P_1\) 持有资源 \(R_1\),并请求资源 \(R_2\)
• 进程 \(P_2\) 持有资源 \(R_2\),并请求资源 \(R_1\)
A cycle exists: \(P_1 \to R_2 \to P_2 \to R_1 \to P_1\).

图表示:
\(P_1 \to R_2\):进程 \(P_1\) 请求资源 \(R_2\)
\(R_1 \to P_1\):资源 \(R_1\) 分配给进程 \(P_1\)
\(P_2 \to R_1\):进程 \(P_2\) 请求资源 \(R_1\)
\(R_2 \to P_2\):资源 \(R_2\) 分配给进程 \(P_2\)
Cycle exists, so deadlock occurs.


示例 3:多资源实例的不确定情况

资源分配图:
• 进程 \(P_1\) 持有资源 \(R_1\)\(R_2\)
• 进程 \(P_2\) 持有资源 \(R_3\),并请求资源 \(R_1\)
• 进程 \(P_3\) 持有资源 \(R_2\),并请求资源 \(R_3\)
No deadlock because multiple instances of resources exist, and processes can eventually proceed.

图表示:
\(P_1 \to R_2, R_1 \to P_1\)
\(P_2 \to R_1, R_3 \to P_2\)
\(P_3 \to R_3, R_2 \to P_3\)
No cycle exists, so no deadlock.


6. 死锁建模的基本事实

无环图:
Acyclic Graph:
• 如果资源分配图中没有环,则系统中不存在死锁。
If the resource allocation graph contains no cycles, there is no deadlock in the system.

有环图:
Cyclic Graph:
• 如果资源分配图中存在环,则可能存在死锁。
If the resource allocation graph contains cycles, deadlock may occur.
单资源实例:
◦ 如果每个资源类型只有一个实例,则图中存在环意味着一定存在死锁。
If there is only one instance per resource type, a cycle in the graph guarantees a deadlock.
多资源实例:
◦ 如果每个资源类型有多个实例,则图中存在环仅表示可能存在死锁。
If there are multiple instances per resource type, a cycle in the graph indicates the possibility of deadlock.


总结

资源分配图是分析死锁的重要工具,通过图的顶点和边可以直观地表示进程和资源之间的关系。
The Resource Allocation Graph is an important tool for analyzing deadlocks, as it intuitively represents the relationships between processes and resources.

死锁的发生条件可以通过资源分配图中的环来判断:
Deadlock conditions can be determined by cycles in the Resource Allocation Graph:
1. 无环图: 无死锁。
Acyclic graph: No deadlock.
2. 有环图:
◦ 单资源实例:一定存在死锁。
Single resource instance: Deadlock is guaranteed.
◦ 多资源实例:可能存在死锁。
Multiple resource instances: Deadlock is possible.

通过资源分配图,可以有效地检测和分析系统中的死锁情况,为死锁预防和恢复提供依据。
Using the Resource Allocation Graph, deadlocks in a system can be effectively detected and analyzed, providing a basis for deadlock prevention and recovery.


死锁处理方法(Methods for Handling Deadlocks)


1. 忽略死锁(The Ostrich Algorithm)

定义:
Definition:
• 假设死锁不会发生,或者发生的概率极低,因此忽略死锁问题。
Pretend there is no problem by assuming that deadlocks either do not occur or occur with very low probability.

适用场景:
Applicable Scenarios:
• 死锁发生的概率非常低。
Deadlocks occur very rarely.
• 预防死锁的成本过高。
The cost of prevention is high.

优点:
Advantages:
• 简单易实现,适合对可靠性要求不高的系统。
Simple and easy to implement, suitable for systems with low reliability requirements.

缺点:
Disadvantages:
• 不适用于需要高可靠性的系统。
Not suitable for systems requiring high reliability.

实际应用:
Real-World Applications:
• UNIX 和 Windows 系统采用了这种方法。
UNIX and Windows adopt this approach.
• 这是一种便利性正确性之间的权衡。
A trade-off between convenience and correctness.


2. 死锁检测与恢复(Deadlock Detection and Recovery)

定义:
Definition:
• 允许系统进入死锁状态,但通过定期运行死锁检测算法来发现死锁,并通过恢复算法解除死锁。
Allow the system to enter a deadlock state, but periodically run a Deadlock Detection algorithm to find deadlocks and a Recovery algorithm to resolve them.

检测算法:
Detection Algorithm:
• 使用资源分配图(Resource Allocation Graph, RAG)来检测系统中是否存在死锁。
Use a Resource Allocation Graph (RAG) to detect deadlocks in the system.单资源实例:
◦ 如果图中存在环,则一定存在死锁。
If a cycle exists in the graph, a deadlock is guaranteed.多资源实例:
◦ 如果图中存在环,则可能存在死锁。
If a cycle exists in the graph, a deadlock is possible.

恢复算法:
Recovery Algorithm:
终止进程:
◦ 终止部分进程以释放资源,解除死锁。
Terminate some processes to release resources and resolve the deadlock.
资源抢占:
◦ 强制回收某些进程的资源并分配给其他进程。
Forcefully reclaim resources from some processes and allocate them to others.

优点:
Advantages:
• 系统可以在死锁发生后恢复,适合高可靠性系统。
The system can recover after a deadlock occurs, making it suitable for highly reliable systems.

缺点:
Disadvantages:
• 检测和恢复过程可能带来额外的开销。
Detection and recovery processes may incur additional overhead.


3. 死锁避免(Deadlock Avoidance)

定义:
Definition:
• 在分配资源之前,系统会预测是否会导致死锁,从而避免进入不安全状态。
Before allocating resources, the system predicts whether a deadlock will occur, thereby avoiding unsafe states.

算法:
Algorithms:
银行家算法(Banker's Algorithm):
◦ 通过模拟资源分配过程,确保系统始终处于安全状态。
Simulates resource allocation to ensure the system remains in a safe state.

优点:
Advantages:
• 系统不会进入死锁状态,资源利用率较高。
The system will not enter a deadlock state, and resource utilization is higher.

缺点:
Disadvantages:
• 需要提前知道进程的资源需求,实现复杂。
Requires prior knowledge of process resource requirements, making implementation complex.


4. 死锁预防(Deadlock Prevention)

定义:
Definition:
• 通过破坏死锁的四个必要条件之一来预防死锁的发生。
Prevent deadlocks by breaking one of the four necessary conditions for deadlocks.

死锁的四个必要条件:
Four Necessary Conditions for Deadlocks:
1. 互斥条件(Mutual Exclusion Condition):
◦ 每个资源一次只能分配给一个进程,或者处于可用状态。
Each resource is assigned to one process or is available.
2. 占有并等待条件(Hold and Wait Condition):
◦ 持有资源的进程可以请求额外的资源。
A process holding resources can request additional resources.
3. 不可抢占条件(No Preemption Condition):
◦ 已分配的资源不能被强制收回,必须由持有进程显式释放。
Previously granted resources cannot be forcibly taken away; they must be explicitly released by the holding process.
4. 循环等待条件(Circular Wait Condition):
◦ 必须存在一个由两个或更多进程组成的循环链,每个进程都在等待下一个进程持有的资源。
There must be a circular chain of two or more processes, where each is waiting for a resource held by the next member of the chain.

预防方法:
Prevention Methods:
1. 破坏互斥条件:
◦ 允许多个进程共享某些资源(如只读文件)。
Allow multiple processes to share certain resources (e.g., read-only files).
2. 破坏占有并等待:
◦ 要求进程在请求资源时一次性申请所有需要的资源。
Require processes to request all needed resources at once.
3. 破坏不可抢占:
◦ 允许强制回收资源(仅适用于可抢占资源)。
Allow forced reclamation of resources (only applicable to preemptable resources).
4. 破坏循环等待:
◦ 对资源进行编号,要求进程按编号顺序请求资源。
Number resources and require processes to request them in order.

优点:
Advantages:
• 系统不会进入死锁状态,可靠性高。
The system will not enter a deadlock state, ensuring high reliability.

缺点:
Disadvantages:
• 可能降低资源利用率。
May reduce resource utilization.


5. 死锁检测算法的详细实现

5.1 检测单资源类型的死锁

方法:
• 使用资源分配图(RAG)检测图中是否存在环。
Use a Resource Allocation Graph (RAG) to detect cycles in the graph.

步骤:
1. 记录资源所有权和请求:
◦ 记录每个进程持有的资源和请求的资源。
Record the resources held and requested by each process. 2. 检测环:
◦ 如果图中存在环,则说明存在死锁。
If a cycle exists in the graph, it indicates a deadlock.


5.2 有向图中检测环的算法

数据结构:
\(L\):一个节点列表,用于记录访问路径。
\(L\): A list of nodes to record the traversal path.
• 弧标记:标记已检查的弧,防止重复检查。
Arcs are marked to indicate they have been inspected, preventing repeated inspections.

算法步骤:
1. 初始化:
◦ 将 \(L\) 初始化为空列表,所有弧标记为未检查。
Initialize \(L\) as an empty list and mark all arcs as unmarked. 2. 遍历节点:
◦ 对于图中的每个节点 \(N\),执行以下步骤:
For each node \(N\) in the graph, perform the following steps: ◦ 将当前节点加入 \(L\)
Add the current node to the end of \(L\). ◦ 如果当前节点在 \(L\) 中出现两次,则图中存在环,算法终止。
If the node appears twice in \(L\), a cycle exists, and the algorithm terminates. ◦ 检查当前节点是否有未标记的出弧:
Check if the current node has any unmarked outgoing arcs:
▪ 如果有,随机选择一个未标记的弧并标记,移动到新节点,重复步骤 2。
If yes, pick an unmarked outgoing arc, mark it, move to the new node, and repeat step 2. ▪ 如果没有,回溯到上一个节点,重复步骤 3。
If no, backtrack to the previous node and repeat step 3. ◦ 如果回溯到初始节点且未发现环,则图中无环,算法终止。
If backtracking reaches the initial node without finding a cycle, the graph is acyclic, and the algorithm terminates.


6. 死锁处理方法的对比总结

方法 特点 优点 缺点
忽略死锁(Ostrich) 假设死锁不会发生。 简单易实现,适合低可靠性系统。 不适用于高可靠性系统。
检测与恢复 允许死锁发生,定期检测并恢复。 系统可以在死锁发生后恢复,适合高可靠性系统。 检测和恢复过程可能带来额外开销。
动态避免(Avoidance) 在分配资源前预测是否会导致死锁,避免进入不安全状态。 系统不会进入死锁状态,资源利用率较高。 需要提前知道进程的资源需求,实现复杂。
预防(Prevention) 破坏死锁的四个必要条件之一,预防死锁发生。 系统不会进入死锁状态,可靠性高。 可能降低资源利用率。

总结

死锁是操作系统中常见的问题,处理方法包括忽略、检测与恢复、动态避免和预防。
Deadlocks are a common problem in operating systems, with handling methods including ignoring, detection and recovery, avoidance, and prevention.

忽略死锁适用于低可靠性系统,而检测与恢复、动态避免和预防适用于高可靠性系统。
Ignoring deadlocks is suitable for low-reliability systems, while detection and recovery, avoidance, and prevention are suitable for high-reliability systems.

动态避免和预防通过资源分配策略避免死锁,但可能降低资源利用率。
Dynamic avoidance and prevention avoid deadlocks through resource allocation strategies but may reduce resource utilization.

检测与恢复允许死锁发生,但通过算法检测和恢复,适合需要高可靠性的系统。
Detection and recovery allow deadlocks to occur but resolve them through algorithms, making them suitable for highly reliable systems.

死锁检测与恢复的详细讲解


1. 死锁检测算法

1.1 单资源类型的死锁检测

算法目标:
Goal:
• 检测资源分配图中是否存在环,若存在环,则说明可能存在死锁。
Detect cycles in the Resource Allocation Graph (RAG). If a cycle exists, it indicates a possible deadlock.

算法步骤:
Steps:
1. 初始化一个空列表 \(L\),用于记录访问路径。
Initialize an empty list \(L\) to record the traversal path.
2. 从任意节点开始遍历图:
Traverse the graph starting from any node:
◦ 将当前节点加入 \(L\)
Add the current node to \(L\).
◦ 如果当前节点在 \(L\) 中出现两次,则说明存在环,算法终止。
If the node appears twice in \(L\), a cycle exists, and the algorithm terminates.
◦ 如果当前节点有未标记的出弧,则随机选择一个未标记的弧并标记,移动到新节点,重复步骤 2。
If the node has unmarked outgoing arcs, randomly pick an unmarked arc, mark it, move to the new node, and repeat step 2.
◦ 如果当前节点没有未标记的出弧,则回溯到上一个节点,重复步骤 3。
If the node has no unmarked outgoing arcs, backtrack to the previous node and repeat step 3.
3. 如果回溯到初始节点且未发现环,则图中无环,算法终止。
If backtracking reaches the initial node without finding a cycle, the graph is acyclic, and the algorithm terminates.

示例 1:无环图路径记录:
\(L = \{R, A, S\}\)
◦ 从 \(R\)\(A\),再到 \(S\)\(S\) 是死胡同(没有出弧)。
From \(R\) to \(A\), then to \(S\), which is a dead end.
◦ 回溯到 \(A\),再回溯到 \(R\),未发现环。
Backtrack to \(A\), then to \(R\), no cycle detected.
结论: 图中无环,无死锁。
Conclusion: No cycle exists, no deadlock.

示例 2:有环图路径记录:
\(L = \{B, T, E, V, G, U, D\}\)
◦ 从 \(B\) 开始,经过 \(T, E, V, G, U\),到达 \(D\)
From \(B\), traverse \(T, E, V, G, U\), and reach \(D\).
◦ 从 \(D\) 随机选择弧到 \(S\),但 \(S\) 是死胡同。
From \(D\), randomly pick an arc to \(S\), which is a dead end.
◦ 回溯到 \(D\),选择另一条弧回到 \(T\),此时 \(T\)\(L\) 中出现两次,说明存在环。
Backtrack to \(D\), pick another arc back to \(T\), and \(T\) appears twice in \(L\), indicating a cycle.
结论: 图中存在环,可能存在死锁。
Conclusion: A cycle exists, indicating a possible deadlock.

img

1.2 多资源类型的死锁检测

算法目标:
Goal:
• 检测多资源类型的情况下,系统中是否存在死锁。
Detect deadlocks in a system with multiple instances of each resource type.

所需数据结构:
Data Structures Needed:
1. \(C_{ij}\) 每个进程 \(P_i\) 对资源类型 \(R_j\) 的当前需求矩阵。
\(C_{ij}\): Current demand matrix for each process \(P_i\) for resource type \(R_j\).
2. \(A_j\) 每种资源类型 \(R_j\) 的可用实例数。
\(A_j\): Available instances of each resource type \(R_j\).
3. \(E_j\) 每种资源类型 \(R_j\) 的总实例数。
\(E_j\): Total instances of each resource type \(R_j\).
4. \(C_{ij} + A_j = E_j\) 资源分配的基本公式。
\(C_{ij} + A_j = E_j\): Basic formula for resource allocation.

算法步骤:
Steps:
1. 初始化所有进程为未标记状态。
Initialize all processes as unmarked.
2. 找到一个未标记的进程 \(P_i\),其资源需求 \(C_{ij}\) 小于等于可用资源 \(A_j\)
Find an unmarked process \(P_i\) whose resource demand \(C_{ij} \leq A_j\).
3. 如果找到这样的进程:
If such a process is found:
◦ 将 \(C_{ij}\) 的值加到 \(A_j\) 中,表示释放资源。
Add \(C_{ij}\) to \(A_j\), indicating resource release.
◦ 标记进程 \(P_i\),表示该进程已完成。
Mark process \(P_i\), indicating it has completed.
◦ 回到步骤 2,继续寻找下一个未标记的进程。
Go back to step 2 and continue searching for the next unmarked process.
4. 如果没有找到这样的进程,则算法终止。
If no such process is found, the algorithm terminates.
5. 未标记的进程即为死锁进程。
Unmarked processes are deadlocked.


1.3 多资源类型检测的示例

场景描述:
Scenario Description:
• 系统中有多种资源类型,每个资源类型有多个实例。
There are multiple resource types in the system, and each type has multiple instances.
• 进程 \(P_1, P_2, P_3\) 分别持有和请求不同的资源。
Processes \(P_1, P_2, P_3\) hold and request different resources.

检测过程:
Detection Process:
1. 初始化 \(A_j\) 为可用资源数。
Initialize \(A_j\) as the number of available resources.
2. 找到一个进程 \(P_i\),其资源需求 \(C_{ij} \leq A_j\)
Find a process \(P_i\) where \(C_{ij} \leq A_j\).
3. 更新 \(A_j\) 并标记进程 \(P_i\)
Update \(A_j\) and mark process \(P_i\).
4. 重复上述步骤,直到没有满足条件的进程。
Repeat the above steps until no more processes satisfy the condition.
5. 未标记的进程即为死锁进程。
Unmarked processes are deadlocked.


2. 死锁恢复(Recovery from Deadlock)

恢复的目标:
Goal of Recovery:
• 解除死锁状态,释放资源,使系统恢复正常运行。
Resolve the deadlock state, release resources, and restore normal system operation.

恢复方法:

2.1 通过抢占恢复(Recovery through Preemption)

定义:
Definition:
• 从某些进程中抢占资源并分配给其他进程,以解除死锁。
Take resources from some processes and allocate them to others to resolve the deadlock.

实现方式:
Implementation:
1. 根据资源的性质选择抢占的进程。
Select processes for preemption based on the nature of the resources.
2. 抢占资源后,释放被抢占进程的状态。
After preemption, release the state of the preempted processes.

优点:
Advantages:
• 不需要终止进程,资源利用率较高。
Does not require terminating processes, ensuring higher resource utilization.

缺点:
Disadvantages:
• 抢占可能导致某些进程状态丢失,需要额外的恢复机制。
Preemption may cause loss of process state, requiring additional recovery mechanisms.


2.2 通过回滚恢复(Recovery through Rollback)

定义:
Definition:
• 定期保存进程的检查点(checkpoint),在检测到死锁时,将进程回滚到之前的状态并重新运行。
Periodically save checkpoints of processes. When a deadlock is detected, roll back the processes to their previous states and restart them.

实现方式:
Implementation:
1. 定期保存进程的状态(如寄存器值、内存状态等)。
Periodically save the state of processes (e.g., register values, memory state).
2. 检测到死锁时,选择一个或多个进程进行回滚。
When a deadlock is detected, select one or more processes to roll back.
3. 将进程恢复到之前的检查点状态,并重新运行。
Restore the process to its previous checkpoint state and restart it.

优点:
Advantages:
• 不需要终止进程,资源利用率较高。
Does not require terminating processes, ensuring higher resource utilization.
• 回滚后可以继续完成任务。
Processes can continue their tasks after rollback.

缺点:
Disadvantages:
• 需要额外的存储空间保存检查点。
Requires additional storage space for checkpoints.
• 回滚可能导致任务延迟。
Rollback may cause task delays.


3. 死锁检测与恢复的对比总结

方法 特点 优点 缺点
检测与恢复 允许死锁发生,定期检测并恢复。 系统可以在死锁发生后恢复,适合高可靠性系统。 检测和恢复过程可能带来额外开销。
通过抢占恢复 从某些进程中抢占资源并分配给其他进程。 不需要终止进程,资源利用率较高。 抢占可能导致某些进程状态丢失,需要额外的恢复机制。
通过回滚恢复 定期保存检查点,在检测到死锁时回滚进程状态。 不需要终止进程,资源利用率较高,回滚后可以继续完成任务。 需要额外的存储空间保存检查点,回滚可能导致任务延迟。

总结

死锁检测与恢复是操作系统中重要的机制,用于处理系统中可能发生的死锁问题。
Deadlock detection and recovery are important mechanisms in operating systems for handling potential deadlocks.

检测算法通过资源分配图或向量比较发现死锁,恢复方法包括抢占和回滚。
Detection algorithms discover deadlocks through Resource Allocation Graphs or vector comparisons, while recovery methods include preemption and rollback.

选择合适的恢复方法需要权衡资源利用率、任务延迟和系统复杂性。
Choosing the appropriate recovery method requires balancing resource utilization, task delays, and system complexity.


死锁避免(Deadlock Avoidance)


1. 死锁避免的基本概念

定义:
Definition:
• 死锁避免算法通过动态检查资源分配状态,确保系统永远不会进入循环等待条件(Circular Wait Condition)。
Deadlock avoidance algorithms dynamically examine the resource allocation state to ensure that there can never be a circular wait condition.

特点:
Characteristics:
1. 需要额外的先验信息:
◦ 系统需要知道每个进程可能需要的每种资源的最大数量。
The system requires some additional a priori information, such as the maximum number of each type of resource that each process may need. 2. 目标:
◦ 避免系统进入不安全状态,从而防止死锁的发生。
The goal is to prevent the system from entering an unsafe state, thereby avoiding deadlocks.

应用场景:
Application Scenarios:
• 适用于需要高可靠性的系统,例如银行系统、实时系统等。
Suitable for highly reliable systems, such as banking systems, real-time systems, etc.


2. 基于安全状态的死锁避免算法

安全状态的定义:
Definition of a Safe State:
• 如果系统处于安全状态,则不存在死锁,并且可以通过某种顺序运行所有进程来满足所有未完成的资源请求。
A state is safe if the system is not in a deadlock and there is a way to satisfy all pending requests by running the processes in some order.

安全序列(Safe Sequence):
Safe Sequence:
• 安全序列是指一组进程的执行顺序,按照该顺序运行所有进程可以满足所有资源请求,而不会导致死锁。
A safe sequence is an order of process execution in which all resource requests can be satisfied without causing a deadlock.

算法目标:
Goal of the Algorithm:
• 在每次资源分配时,系统必须判断立即分配资源是否会将系统置于安全状态。
The system must determine whether immediately allocating resources will leave the system in a safe state.


3. 安全状态与不安全状态

3.1 安全状态的示例

场景描述:
Scenario Description:
• 系统中有两个进程 \(B\)\(C\),以及三种资源类型 \(R_1, R_2, R_3\)
The system has two processes \(B\) and \(C\), and three resource types \(R_1, R_2, R_3\).
• 当前资源分配状态如下:
Current resource allocation state:
\(B\) 已分配资源 \(R_1\)\(R_2\),并请求 \(R_3\)
\(B\) has been allocated \(R_1\) and \(R_2\), and is requesting \(R_3\).
\(C\) 已分配资源 \(R_3\),并请求 \(R_1\)
\(C\) has been allocated \(R_3\), and is requesting \(R_1\).
◦ 系统中有足够的资源满足 \(B\)\(C\) 的请求。

安全序列:
Safe Sequence:
• 假设 \(B\) 先完成并释放资源 \(R_3\),然后 \(C\) 可以完成并释放资源 \(R_1\)
Assume \(B\) completes first and releases \(R_3\), then \(C\) can complete and release \(R_1\).
• 安全序列为:\(B \to C\)
Safe sequence: \(B \to C\).


3.2 不安全状态的示例

场景描述:
Scenario Description:
• 系统中有两个进程 \(B\)\(C\),以及三种资源类型 \(R_1, R_2, R_3\)
The system has two processes \(B\) and \(C\), and three resource types \(R_1, R_2, R_3\).
• 当前资源分配状态如下:
Current resource allocation state:
\(B\) 已分配资源 \(R_1\),并请求 \(R_3\)
\(B\) has been allocated \(R_1\), and is requesting \(R_3\).
\(C\) 已分配资源 \(R_3\),并请求 \(R_1\)
\(C\) has been allocated \(R_3\), and is requesting \(R_1\).
◦ 系统中没有足够的资源同时满足 \(B\)\(C\) 的请求。

不安全状态的原因:
Reason for Unsafe State:
• 如果 \(B\)\(C\) 同时持有部分资源并等待对方释放资源,则系统可能进入死锁状态。
If \(B\) and \(C\) each hold part of the resources and wait for the other to release resources, the system may enter a deadlock state.


4. 死锁避免的基本事实

安全状态与死锁的关系:
Relationship Between Safe State and Deadlock:
1. 如果系统处于安全状态,则不存在死锁。
If the system is in a safe state, there are no deadlocks.
2. 如果系统处于不安全状态,则可能存在死锁。
If the system is in an unsafe state, a deadlock may occur.
3. 死锁避免的目标是确保系统永远不会进入不安全状态。
The goal of deadlock avoidance is to ensure that the system never enters an unsafe state.

img

5. 银行家算法(Banker's Algorithm)

定义:
Definition:
• 银行家算法是一种经典的死锁避免算法,通过模拟资源分配过程,确保系统始终处于安全状态。
The Banker's Algorithm is a classic deadlock avoidance algorithm that ensures the system remains in a safe state by simulating resource allocation.

算法步骤:
Steps of the Algorithm:
1. 初始化:
◦ 系统记录每个进程的最大资源需求 \(Max\)、已分配资源 \(Allocation\)、剩余需求 \(Need\),以及可用资源 \(Available\)
The system records the maximum resource demand \(Max\), allocated resources \(Allocation\), remaining demand \(Need\), and available resources \(Available\) for each process.
2. 资源请求检查:
◦ 当进程 \(P_i\) 请求资源时,检查分配后系统是否仍处于安全状态。
When process \(P_i\) requests resources, check whether the system remains in a safe state after allocation.
3. 安全状态检查:
◦ 使用安全序列算法,判断是否存在一个安全序列,使得所有进程都能完成。
Use the safe sequence algorithm to determine whether a safe sequence exists that allows all processes to complete.
4. 资源分配:
◦ 如果安全状态检查通过,则分配资源;否则拒绝请求。
If the safe state check passes, allocate resources; otherwise, deny the request.

示例:
Example:
• 假设系统中有两个进程 \(P_1\)\(P_2\),资源类型为 \(R_1, R_2\)
Assume there are two processes \(P_1\) and \(P_2\), with resource types \(R_1, R_2\).
\(P_1\) 的最大需求为 \((3, 2)\),已分配 \((1, 0)\),剩余需求为 \((2, 2)\)
\(P_1\): Max = (3, 2), Allocation = (1, 0), Need = (2, 2).
\(P_2\) 的最大需求为 \((1, 3)\),已分配 \((0, 2)\),剩余需求为 \((1, 1)\)
\(P_2\): Max = (1, 3), Allocation = (0, 2), Need = (1, 1).
◦ 可用资源为 \((1, 1)\)
Available = (1, 1).
• 如果 \(P_1\) 请求资源 \((1, 1)\),系统会检查分配后是否仍处于安全状态。
If \(P_1\) requests \((1, 1)\), the system checks whether the system remains in a safe state after allocation.


6. 安全状态与不安全状态的对比总结

状态 定义 特点
安全状态 系统中不存在死锁,并且存在一个安全序列使得所有进程都能完成。 - 系统可以正常运行,不会发生死锁。
- 资源分配策略需要确保系统始终处于安全状态。
不安全状态 系统中可能存在死锁,因为没有安全序列使得所有进程都能完成。 - 系统可能进入死锁状态,需要通过死锁避免或检测机制来恢复。
img

7. 死锁避免的优缺点

优点:
Advantages:
1. 预防死锁:
◦ 系统不会进入死锁状态,可靠性高。
Prevents deadlocks, ensuring high reliability.
2. 资源利用率较高:
◦ 通过动态检查资源分配状态,可以更高效地利用资源。
Higher resource utilization through dynamic checking of resource allocation states.

缺点:
Disadvantages:
1. 复杂性高:
◦ 需要额外的先验信息,并且算法复杂度较高。
High complexity, requiring additional a priori information and complex algorithms.
2. 可能降低资源利用率:
◦ 过于保守的资源分配策略可能导致资源利用率降低。
May reduce resource utilization due to overly conservative allocation strategies.


总结

死锁避免通过动态检查资源分配状态,确保系统永远不会进入不安全状态,从而预防死锁的发生。
Deadlock avoidance dynamically examines resource allocation states to ensure the system never enters an unsafe state, thereby preventing deadlocks.

安全状态是死锁避免的核心概念,系统必须确保每次资源分配后仍处于安全状态。
Safe states are the core concept of deadlock avoidance, and the system must ensure that it remains in a safe state after each resource allocation.

银行家算法是死锁避免的经典实现,通过模拟资源分配过程,确保系统始终处于安全状态。
The Banker's Algorithm is a classic implementation of deadlock avoidance, ensuring the system remains in a safe state by simulating resource allocation.

死锁避免的优点是预防死锁,缺点是复杂性较高,可能降低资源利用率。
The advantages of deadlock avoidance are prevention of deadlocks, while the disadvantages are higher complexity and potential reduction in resource utilization.


银行家算法(Banker's Algorithm)详解


1. 银行家算法的基本原理

定义:
Definition:
• 银行家算法是一种经典的死锁避免算法,由 Dijkstra 在 1965 年提出。
The Banker's Algorithm is a classic deadlock avoidance algorithm proposed by Dijkstra in 1965.

核心思想:
Core Idea:
• 系统在分配资源之前,模拟资源分配过程,检查分配后系统是否仍处于安全状态。
The system simulates the resource allocation process before allocating resources to check whether the system remains in a safe state after the allocation.

类比:
Analogy:
• 银行家算法类似于银行家在贷款时的风险评估:
◦ 每个客户(进程)告诉银行家其最大贷款需求。
◦ 银行家只在确保贷款不会导致银行破产(系统进入不安全状态)的情况下发放贷款。
The Banker's Algorithm is analogous to a banker assessing loan risks: Each customer (process) tells the banker their maximum loan demand. The banker only lends money if it ensures the bank will not go bankrupt (the system will not enter an unsafe state).

关键概念:
Key Concepts:
1. 安全状态(Safe State):
◦ 系统中存在一个安全序列,使得所有进程都能完成。
A safe state is one where there exists a sequence of resource allocations such that all processes can complete.
2. 不安全状态(Unsafe State):
◦ 系统中不存在安全序列,可能进入死锁状态。
An unsafe state is one where no such sequence exists, and the system may enter a deadlock.


2. 银行家算法的基本假设

进程的资源需求:
Resource Requirements of Processes:
• 每个进程在运行前声明其对每种资源的最大需求 \(Max\)
Each process declares the maximum demand for each resource type before running.
• 进程的实际资源使用量 \(Allocation\) 不超过其声明的最大需求。
The actual resource usage \(Allocation\) of a process does not exceed its declared maximum demand.

系统资源状态:
System Resource State:
• 系统记录当前可用资源 \(Available\)
The system keeps track of the currently available resources \(Available\).
• 系统还记录每个进程的剩余需求 \(Need = Max - Allocation\)
The system also tracks the remaining demand \(Need = Max - Allocation\) for each process.


3. 单资源情况下的银行家算法

场景描述:
Scenario Description:
• 系统中只有一个资源类型 \(R\)
There is only one resource type \(R\) in the system.
• 系统中有 \(n\) 个进程,每个进程声明了其对资源的最大需求 \(Max\)
There are \(n\) processes, each declaring a maximum demand \(Max\) for the resource.

安全状态的定义:
Definition of a Safe State:
• 如果系统中存在一个进程执行序列,使得所有进程都能完成,则系统处于安全状态。
A system is in a safe state if there exists a sequence of process executions such that all processes can complete.

算法步骤:
Steps of the Algorithm:
1. 找到一个进程 \(P_i\),其剩余需求 \(Need[i] \leq Available\)
Find a process \(P_i\) where \(Need[i] \leq Available\).
2. 假设该进程完成并释放资源,更新可用资源 \(Available = Available + Allocation[i]\)
Assume the process completes and releases resources, updating \(Available = Available + Allocation[i]\).
3. 标记该进程为已完成,并重复步骤 1 和 2。
Mark the process as completed and repeat steps 1 and 2.
4. 如果所有进程都被标记为已完成,则系统处于安全状态;否则,系统处于不安全状态。
If all processes are marked as completed, the system is in a safe state; otherwise, it is in an unsafe state.


4. 多资源情况下的银行家算法

场景描述:
Scenario Description:
• 系统中有多种资源类型 \(R_1, R_2, \dots, R_m\)
There are multiple resource types \(R_1, R_2, \dots, R_m\) in the system.
• 系统中有 \(n\) 个进程,每个进程声明了其对每种资源的最大需求 \(Max[i][j]\)
There are \(n\) processes, each declaring a maximum demand \(Max[i][j]\) for each resource type \(R_j\).

数据结构:
Data Structures:
1. \(Max[i][j]\)
◦ 进程 \(P_i\) 对资源类型 \(R_j\) 的最大需求。
The maximum demand of process \(P_i\) for resource type \(R_j\).
2. \(Allocation[i][j]\)
◦ 进程 \(P_i\) 当前已分配的资源 \(R_j\) 的数量。
The number of resources \(R_j\) currently allocated to process \(P_i\).
3. \(Need[i][j]\)
◦ 进程 \(P_i\) 对资源类型 \(R_j\) 的剩余需求,计算公式为:
\[ Need[i][j] = Max[i][j] - Allocation[i][j] \] The remaining demand of process \(P_i\) for resource type \(R_j\), calculated as \(Need[i][j] = Max[i][j] - Allocation[i][j]\).
4. \(Available[j]\)
◦ 当前系统中每种资源类型 \(R_j\) 的可用数量。
The number of available resources of type \(R_j\) in the system.

安全状态检查的步骤:
Steps to Check for a Safe State:
1. 初始化工作向量 \(Work = Available\) 和完成标记数组 \(Finish[i] = false\)
Initialize the work vector \(Work = Available\) and the completion flag array \(Finish[i] = false\).
2. 找到一个进程 \(P_i\),满足:
\(Finish[i] = false\)
\(Need[i][j] \leq Work[j]\) 对所有资源类型 \(R_j\) 成立。
Find a process \(P_i\) such that \(Finish[i] = false\) and \(Need[i][j] \leq Work[j]\) for all resource types \(R_j\).
3. 如果找到这样的进程:
◦ 假设该进程完成并释放资源,更新 \(Work = Work + Allocation[i]\)
If such a process is found, assume it completes and releases resources, updating \(Work = Work + Allocation[i]\).
◦ 标记该进程为已完成,\(Finish[i] = true\)
Mark the process as completed, \(Finish[i] = true\).
◦ 回到步骤 2。
Go back to step 2.
4. 如果所有进程都被标记为已完成,则系统处于安全状态;否则,系统处于不安全状态。
If all processes are marked as completed, the system is in a safe state; otherwise, it is in an unsafe state.


7. 银行家算法的优缺点

优点:
Advantages:
1. 预防死锁:
◦ 系统不会进入死锁状态,可靠性高。
Prevents deadlocks, ensuring high reliability.
2. 动态资源分配:
◦ 系统可以在运行时动态调整资源分配策略。
Allows dynamic resource allocation and adjustment during runtime.

缺点:
Disadvantages:
1. 复杂性高:
◦ 需要额外的先验信息,并且算法复杂度较高。
High complexity, requiring additional a priori information and complex algorithms.
2. 保守性:
◦ 过于保守的资源分配策略可能导致资源利用率降低。
Conservative resource allocation may reduce resource utilization.


总结

银行家算法是一种经典的死锁避免算法,通过模拟资源分配过程,确保系统始终处于安全状态。
The Banker's Algorithm is a classic deadlock avoidance algorithm that ensures the system remains in a safe state by simulating resource allocation.

• **安全状态是银行家算法的核心概念,系统必须确保每次资源分配后仍处于

死锁预防(Deadlock Prevention)

以下是关于死锁预防的详细讲解,包括其基本思想、针对死锁四个必要条件的破坏方法,以及每种方法的优缺点和实际应用场景。


1. 死锁预防的基本思想

定义:
Definition:
• 死锁预防通过破坏死锁的四个必要条件之一,确保系统永远不会进入死锁状态。
Deadlock prevention ensures that the system will never enter a deadlock state by breaking one of the four necessary conditions for deadlocks.

死锁的四个必要条件:
Four Necessary Conditions for Deadlocks:
1. 互斥条件(Mutual Exclusion Condition):
◦ 每个资源一次只能分配给一个进程,或者处于可用状态。
Each resource is assigned to one process or is available.
2. 占有并等待条件(Hold and Wait Condition):
◦ 持有资源的进程可以请求额外的资源。
A process holding resources can request additional resources.
3. 不可抢占条件(No Preemption Condition):
◦ 已分配的资源不能被强制收回,必须由持有进程显式释放。
Previously granted resources cannot be forcibly taken away; they must be explicitly released by the holding process.
4. 循环等待条件(Circular Wait Condition):
◦ 必须存在一个由两个或更多进程组成的循环链,每个进程都在等待下一个进程持有的资源。
There must be a circular chain of two or more processes, where each is waiting for a resource held by the next member of the chain.

预防方法:
Prevention Methods:
• 针对每个条件采取相应的策略,破坏其成立的可能性。
Adopt strategies to break each condition, making it impossible for the condition to hold.


2. 针对互斥条件(Mutual Exclusion Condition)的预防

基本思想:
Basic Idea:
• 尽量避免资源的独占分配,允许多个进程共享某些资源。
Avoid exclusive allocation of resources as much as possible, allowing multiple processes to share certain resources.

具体方法:
Specific Methods:
1. 资源池化(Spooling):
◦ 将某些资源(如打印机)的操作集中到一个守护进程(daemon)中。
Centralize the operation of certain resources (e.g., printers) into a daemon process.
◦ 守护进程独占资源,其他进程通过守护进程间接使用资源。
The daemon exclusively uses the resource, and other processes use the resource indirectly through the daemon.
优点:
◦ 消除了对打印机等资源的竞争,避免了死锁。
Eliminates competition for resources like printers, avoiding deadlocks.
缺点:
◦ 如果池化空间有限,仍可能发生死锁。
If the spooling space is limited, deadlocks may still occur.
◦ 并非所有资源都可以池化(如独占设备)。
Not all resources can be spooled (e.g., exclusive devices).

示例:打印机资源池化
Example: Printer Spooling
• 假设多个进程同时请求打印机资源,守护进程将所有打印任务集中处理。
If multiple processes request the printer resource simultaneously, the daemon processes all print tasks centrally.
• 如果守护进程占用了过多的池化空间,可能导致其他进程无法继续运行,从而引发死锁。
If the daemon occupies too much spooling space, other processes may be unable to proceed, causing a deadlock.


3. 针对占有并等待条件(Hold and Wait Condition)的预防

基本思想:
Basic Idea:
• 要求进程在请求资源时一次性申请所有需要的资源,或者在运行过程中不持有任何资源时才能请求新资源。
Require processes to request all needed resources at once, or not hold any resources while requesting new ones.

具体方法:
Specific Methods:
1. 一次性请求所有资源:
◦ 进程在启动前必须声明并申请所有需要的资源。
Processes must declare and request all required resources before starting.
优点:
◦ 进程不会在运行过程中等待资源,避免了死锁。
Processes do not need to wait for resources during execution, avoiding deadlocks.
缺点:
◦ 进程可能无法在启动时准确知道所需的资源数量。
Processes may not know the exact amount of resources needed at startup.
◦ 可能导致资源利用率降低,因为其他进程无法使用被占用的资源。
May reduce resource utilization, as other processes cannot use the allocated resources.

  1. 释放当前资源再请求新资源:
    ◦ 进程在请求新资源时,必须先释放当前持有的所有资源。
    Processes must release all currently held resources before requesting new ones.
    优点:
    ◦ 减少了资源竞争的可能性。
    Reduces the likelihood of resource competition.
    缺点:
    ◦ 频繁的资源释放和重新分配可能导致性能下降。
    Frequent resource release and reallocation may degrade performance.

4. 针对不可抢占条件(No Preemption Condition)的预防

基本思想:
Basic Idea:
• 允许强制回收某些进程的资源,并将其分配给其他进程。
Allow forced reclamation of resources from some processes and allocate them to others.

具体方法:
Specific Methods:
1. 资源抢占:
◦ 如果一个进程请求的资源已被其他进程占用,则强制回收该资源。
If a process requests a resource held by another process, forcibly reclaim the resource.
问题:
◦ 并非所有资源都可以被抢占(如打印机、磁盘等)。
Not all resources can be preempted (e.g., printers, disks).
◦ 抢占可能导致正在运行的进程失败,需要额外的恢复机制。
Preemption may cause running processes to fail, requiring additional recovery mechanisms.

  1. 资源虚拟化:
    ◦ 将资源的使用抽象化,例如通过将打印任务写入磁盘缓冲区,由守护进程统一处理。
    Virtualize resource usage, such as spooling print tasks to a disk buffer for the daemon to process.
    优点:
    ◦ 减少了直接竞争资源的可能性。
    Reduces direct competition for resources.
    缺点:
    ◦ 并非所有资源都可以虚拟化。
    Not all resources can be virtualized.

5. 针对循环等待条件(Circular Wait Condition)的预防

基本思想:
Basic Idea:
• 对资源进行编号,要求进程按编号顺序请求资源,从而破坏循环等待的可能性。
Number resources and require processes to request them in order, breaking the possibility of circular waiting.

具体方法:
Specific Methods:
1. 全局资源排序:
◦ 为所有资源分配一个全局编号,进程必须按编号从小到大的顺序请求资源。 (正在持有资源的请求进程优先级会更高) Assign a global number to all resources, and processes must request resources in ascending order.
优点:
◦ 简单有效,适用于资源类型较少的情况。
Simple and effective for systems with fewer resource types.
缺点:
◦ 资源编号可能难以确定,增加了编程复杂性。
Resource numbering may be difficult to determine, increasing programming complexity.

  1. 逐步请求资源:
    ◦ 进程每次只能请求一个资源,释放当前资源后再请求下一个资源。
    Processes can request only one resource at a time, releasing the current resource before requesting the next.
    优点:
    ◦ 避免了循环等待的可能性。
    Avoids circular waiting.
    缺点:
    ◦ 频繁的资源请求和释放可能导致性能下降。
    Frequent resource requests and releases may degrade performance.

6. 死锁预防方法的对比总结

方法 破坏的条件 优点 缺点
破坏互斥条件 互斥条件 允许多个进程共享资源,减少竞争。 并非所有资源都可以共享,可能导致池化空间不足。
破坏占有并等待条件 占有并等待条件 减少了进程在运行过程中等待资源的可能性。 进程可能无法提前知道所需资源,可能导致资源利用率降低。
破坏不可抢占条件 不可抢占条件 允许强制回收资源,减少死锁的可能性。 并非所有资源都可以被抢占,可能导致进程失败。
破坏循环等待条件 循环等待条件 通过资源排序或逐步请求资源,避免循环等待。 资源编号可能难以确定,频繁的资源请求和释放可能导致性能下降。

7. 死锁预防的优缺点

优点:
Advantages:
1. 可靠性高:
◦ 系统不会进入死锁状态,适合高可靠性要求的场景。
High reliability; the system will not enter a deadlock state, suitable for scenarios requiring high reliability.
2. 预防性强:
◦ 通过破坏死锁的必要条件,从根本上避免了死锁的发生。
Proactive; fundamentally avoids deadlocks by breaking their necessary conditions.

缺点:
Disadvantages:
1. 资源利用率低:
◦ 某些预防方法可能导致资源利用率降低。
Some prevention methods may reduce resource utilization.
2. 复杂性高:
◦ 需要对资源和进程进行额外的管理和控制。
Requires additional management and control of resources and processes.
3. 灵活性差:
◦ 某些方法(如全局资源排序)可能限制了系统的灵活性。
Some methods (e.g., global resource ordering) may limit system flexibility.


总结

img

死锁预防通过破坏死锁的四个必要条件之一,确保系统永远不会进入死锁状态。
Deadlock prevention ensures that the system will never enter a deadlock state by breaking one of the four necessary conditions for deadlocks.

针对互斥条件、占有并等待条件、不可抢占条件和循环等待条件,分别有不同的预防方法。
There are different prevention methods for mutual exclusion, hold and wait, no preemption, and circular wait conditions.

死锁预防的优点是可靠性高,缺点是可能导致资源利用率降低和复杂性增加。
The advantages of deadlock prevention are high reliability, but it may reduce resource utilization and increase complexity.

在实际系统中,死锁预防通常与其他机制(如死锁检测与恢复)结合使用,以实现更高的系统性能和可靠性。
In real systems, deadlock prevention is often combined with other mechanisms (e.g., deadlock detection and recovery) to achieve higher system performance and reliability.


其他死锁相关问题:两阶段锁、通信死锁、活锁和饥饿

以下是对两阶段锁(Two-Phase Locking)、通信死锁(Communication Deadlocks)、活锁(Livelock)和饥饿(Starvation)的详细讲解,包括它们的定义、特点、示例以及解决方法。


1. 两阶段锁(Two-Phase Locking, 2PL)

定义:
Definition:
• 两阶段锁是一种并发控制协议,用于在事务中管理资源的锁定和解锁。
Two-Phase Locking is a concurrency control protocol used to manage resource locking and unlocking in transactions.

工作原理:
How It Works:
1. 第一阶段(Growing Phase):
◦ 事务尝试逐个锁定它需要的所有记录。
The transaction tries to lock all the records it needs, one at a time.
◦ 如果所需的记录已被锁定,则事务回滚并重新开始。
If a required record is already locked, the transaction rolls back and restarts.
2. 第二阶段(Shrinking Phase):
◦ 事务成功完成第一阶段后,开始执行更新操作。
After successfully completing the first phase, the transaction begins performing updates.
◦ 在此阶段,事务只能释放锁,不能再请求新的锁。
In this phase, the transaction can only release locks and cannot request new ones.

特点:
Characteristics:
• 类似于死锁预防中的“一次性请求所有资源”策略。
Similar to the deadlock prevention strategy of requesting all resources at once.
• 如果事务在第一阶段成功完成,则不会发生死锁。
If the transaction successfully completes the first phase, no deadlock will occur.

优缺点:
Advantages and Disadvantages:
优点:
◦ 简单有效,避免了事务间的死锁。
Simple and effective, avoids deadlocks between transactions.
◦ 适用于需要严格顺序访问资源的场景。
Suitable for scenarios requiring strict sequential access to resources.
缺点:
◦ 如果事务需要频繁回滚,可能导致性能下降。
If the transaction needs to roll back frequently, performance may degrade.
◦ 不适用于需要动态调整资源访问顺序的场景。
Not suitable for scenarios requiring dynamic adjustment of resource access order.


2. 通信死锁(Communication Deadlocks)

定义:
Definition:
• 通信死锁是一种特殊的死锁,发生在进程之间通过消息传递进行通信时。
Communication deadlock is a special type of deadlock that occurs when processes communicate via message passing.

特点:
Characteristics:
• 每个进程都在等待对方发送消息或事件,从而导致所有进程都被阻塞。
Each process is waiting for the other to send a message or event, causing all processes to be blocked.

示例:
Example:
场景描述:
◦ 进程 A 向进程 B 发送请求消息后阻塞,等待 B 的回复。
◦ 如果请求消息丢失,B 会阻塞等待 A 的请求消息,而 A 则阻塞等待 B 的回复。
Scenario Description:
◦ Process A sends a request message to process B and blocks, waiting for a reply from B.
◦ If the request message is lost, B blocks waiting for a request from A, while A blocks waiting for a reply from B.
解决方法:
◦ 使用超时机制(Timeout):
◦ 如果进程在一定时间内未收到回复,则重发消息或终止等待。
Use a timeout mechanism: If a process does not receive a reply within a certain time, it retransmits the message or terminates the wait.


3. 活锁(Livelock)

定义:
Definition:
• 活锁是一种特殊的状态,进程虽然没有被阻塞,但无法取得进展。
Livelock is a special state where processes are not blocked but cannot make progress.

特点:
Characteristics:
• 活锁与死锁的区别:
死锁: 进程被阻塞,无法继续执行。
活锁: 进程在运行,但无法取得进展。
Deadlock: Processes are blocked and cannot continue execution.
Livelock: Processes are running but cannot make progress.

示例:
Example:
场景描述:
◦ 进程 A 和进程 B 分别持有资源 \(R_1\)\(R_2\),并试图获取对方持有的资源。
◦ 如果两个进程都采用“忙等待”(Polling)的方式尝试获取资源,则它们会不断重试,但始终无法取得进展。
Scenario Description:
◦ Process A and process B each hold resource \(R_1\) and \(R_2\), respectively, and attempt to acquire the resource held by the other.
◦ If both processes use a "busy waiting" (polling) approach to acquire the resource, they will keep retrying but never make progress.

解决方法:
Solutions:
1. 引入随机性:
◦ 在重试时引入随机延迟,避免两个进程同时重试。
Introduce randomness: Add random delays during retries to avoid simultaneous retries.
2. 优先级机制:
◦ 为进程分配优先级,确保某些进程可以优先获取资源。
Use a priority mechanism: Assign priorities to processes to ensure some processes can acquire resources first.


4. 饥饿(Starvation)

定义:
Definition:
• 饥饿是一种资源分配问题,某些进程由于资源分配策略的不公平性,长时间无法获得所需资源。
Starvation is a resource allocation problem where some processes cannot obtain the required resources for a long time due to unfair resource allocation policies.

特点:
Characteristics:
• 饥饿与死锁的区别:
死锁: 所有相关进程都被永久阻塞。
饥饿: 某些进程长时间无法获得资源,但并非所有进程都被阻塞。
Deadlock: All related processes are permanently blocked.
Starvation: Some processes cannot obtain resources for a long time, but not all processes are blocked.

示例:
Example:
场景描述:
◦ 系统采用“最短作业优先”(Shortest Job First, SJF)策略分配资源。
◦ 如果系统中存在大量短作业,则长作业可能会被无限期推迟。
Scenario Description:
◦ The system uses the "Shortest Job First" (SJF) policy to allocate resources.
◦ If there are many short jobs in the system, long jobs may be postponed indefinitely.

解决方法:
Solutions:
1. 公平调度策略:
◦ 使用“先来先服务”(First Come, First Served, FCFS)策略,确保所有进程都能公平地获得资源。
Use a fair scheduling policy: Use the "First Come, First Served" (FCFS) policy to ensure all processes can fairly obtain resources.
2. 动态优先级调整:
◦ 动态调整进程的优先级,避免某些进程长期得不到资源。
Dynamically adjust process priorities to prevent certain processes from being neglected for a long time.


5. 活锁与饥饿的对比总结

问题 定义 特点
活锁(Livelock) 进程在运行,但无法取得进展。 - 进程未被阻塞,但由于不断重试或竞争资源而无法完成。
- 类似于死锁,但进程并未被阻塞。
饥饿(Starvation) 某些进程由于资源分配策略的不公平性,长时间无法获得所需资源。 - 某些进程长期得不到资源,但并非所有进程都被阻塞。
- 可能由不公平的调度策略或资源分配算法引起。

6. 活锁与饥饿的解决方法对比

问题 解决方法
活锁(Livelock) 1. 引入随机性:在重试时添加随机延迟,避免进程同时重试。
2. 优先级机制:为进程分配优先级,确保某些进程可以优先获取资源。
饥饿(Starvation) 1. 公平调度策略:使用“先来先服务”策略,确保所有进程都能公平地获得资源。
2. 动态优先级调整:动态调整进程的优先级,避免某些进程长期得不到资源。

7. 总结

两阶段锁(2PL):
• 通过分阶段锁定资源,避免事务间的死锁。
Two-Phase Locking avoids deadlocks between transactions by locking resources in phases.

通信死锁:
• 发生在进程间通过消息传递进行通信时,通常可以通过超时机制解决。
Communication deadlocks occur during inter-process communication and can often be resolved using timeout mechanisms.

活锁:
• 进程未被阻塞,但由于不断重试或竞争资源而无法完成。
Livelock occurs when processes are not blocked but cannot complete due to constant retries or resource competition.

饥饿:
• 某些进程由于资源分配策略的不公平性,长时间无法获得所需资源。
Starvation occurs when some processes cannot obtain the required resources for a long time due to unfair resource allocation policies.

解决方法:
• 针对活锁,可以引入随机性或优先级机制;针对饥饿,可以采用公平调度策略或动态优先级调整。
For livelock, randomness or priority mechanisms can be introduced; for starvation, fair scheduling policies or dynamic priority adjustments can be used.

死锁处理的总结与权衡

以下是对死锁处理的总结,包括死锁检测与避免的成本分析、权衡方法、以及实际系统中的常用策略。


1. 死锁处理的基本问题

死锁的不可避免性:
Inevitability of Deadlocks:
• 在复杂的系统中,完全避免死锁是非常困难的,尤其是在资源分配和进程调度复杂的情况下。
In complex systems, it is very difficult to completely avoid deadlocks, especially in cases with complex resource allocation and process scheduling.

死锁处理的两种主要方法:
Two Main Approaches to Handle Deadlocks:
1. 死锁检测与恢复(Detection and Recovery):
◦ 允许死锁发生,但通过定期检测死锁并采取恢复措施来解除死锁。
Allow deadlocks to occur but detect them periodically and take recovery measures to resolve them.
2. 死锁避免(Avoidance):
◦ 在资源分配之前,通过算法检查是否会导致死锁,从而避免进入不安全状态。
Avoid deadlocks by checking whether resource allocation will lead to a deadlock before allocating resources.


2. 死锁检测与避免的成本分析

死锁检测的成本:
Costs of Deadlock Detection:
1. 资源分配图的维护:
◦ 需要动态维护资源分配图(Resource Allocation Graph, RAG),并在每次资源分配或释放时更新图的状态。
Requires dynamic maintenance of the Resource Allocation Graph (RAG) and updating the graph state during each resource allocation or release.
2. 周期性检测的开销:
◦ 定期运行死锁检测算法(如基于图的环检测算法)会消耗系统资源。
Running deadlock detection algorithms periodically (e.g., graph-based cycle detection) consumes system resources.

死锁避免的成本:
Costs of Deadlock Avoidance:
1. 额外信息的维护:
◦ 需要提前知道每个进程的最大资源需求(如 \(Max[i][j]\)),这可能增加系统的复杂性。
Requires prior knowledge of each process's maximum resource demands (e.g., \(Max[i][j]\)), increasing system complexity.
2. 算法复杂性:
◦ 死锁避免算法(如银行家算法)需要复杂的计算,可能影响系统的实时性和性能。
Deadlock avoidance algorithms (e.g., the Banker's Algorithm) require complex calculations, potentially affecting system real-time performance.

权衡:
Trade-offs:
• 死锁检测与恢复通常适用于资源分配较为动态的系统,而死锁避免适用于对系统可靠性要求较高的场景。
Deadlock detection and recovery are often suitable for systems with dynamic resource allocation, while deadlock avoidance is more appropriate for scenarios requiring high system reliability.


3. 死锁避免的潜在问题

无限延迟(Indefinite Postponement):
Indefinite Postponement:
• 在某些情况下,死锁避免算法可能导致某些进程长时间无法获得资源,从而引发“饥饿”问题。
In some cases, deadlock avoidance algorithms may cause certain processes to be unable to obtain resources for a long time, leading to starvation.
示例:
◦ 在银行家算法中,如果某些进程的资源需求较大,可能会导致这些进程长时间无法获得资源。
Example:
◦ In the Banker's Algorithm, if some processes have large resource demands, they may be unable to obtain resources for a long time.

资源利用率降低:
Reduced Resource Utilization:
• 死锁避免算法可能过于保守,导致资源利用率降低。
Deadlock avoidance algorithms may be overly conservative, reducing resource utilization.
示例:
◦ 在银行家算法中,某些资源可能被保留以满足未来的需求,但实际上并未被使用。
Example:
◦ In the Banker's Algorithm, some resources may be reserved to meet future demands but are not actually used.


4. 实际系统中的死锁处理策略

忽略死锁(Ostrich Algorithm):
Ignoring Deadlocks (Ostrich Algorithm):
定义:
◦ 假设死锁发生的概率非常低,或者死锁的影响可以接受,因此忽略死锁问题。
Assume that the probability of deadlocks is very low, or the impact of deadlocks is acceptable, so the problem is ignored.
优点:
◦ 简单易实现,适合对可靠性要求不高的系统。
Simple and easy to implement, suitable for systems with low reliability requirements.
缺点:
◦ 不适用于需要高可靠性的系统。
Not suitable for systems requiring high reliability.
实际应用:
◦ UNIX 和 Windows 系统采用了这种方法。
UNIX and Windows systems adopt this approach.

检测与恢复(Detection and Recovery):
Detection and Recovery:
定义:
◦ 允许死锁发生,但通过定期检测死锁并采取恢复措施来解除死锁。
Allow deadlocks to occur but detect them periodically and take recovery measures to resolve them.
优点:
◦ 系统可以在死锁发生后恢复,适合高可靠性系统。
The system can recover after a deadlock occurs, making it suitable for highly reliable systems.
缺点:
◦ 检测和恢复过程可能带来额外的开销。
Detection and recovery processes may incur additional overhead.

动态避免(Dynamic Avoidance):
Dynamic Avoidance:
定义:
◦ 在资源分配之前,动态检查资源分配状态,确保不会进入不安全状态。
Dynamically check the resource allocation state before allocating resources to ensure the system does not enter an unsafe state.
优点:
◦ 提高了系统的可靠性。
Improves system reliability.
缺点:
◦ 算法复杂性较高,可能影响系统性能。
The algorithm is complex and may affect system performance.


5. 死锁处理的权衡总结

方法 优点 缺点
忽略死锁(Ostrich Algorithm) 简单易实现,适合低可靠性系统。 不适用于高可靠性系统。
检测与恢复(Detection and Recovery) 系统可以在死锁发生后恢复,适合高可靠性系统。 检测和恢复过程可能带来额外开销。
动态避免(Dynamic Avoidance) 提高系统可靠性,避免进入不安全状态。 算法复杂性高,可能影响系统性能。
死锁避免(Deadlock Avoidance) 预防死锁,确保系统不会进入不安全状态。 可能导致资源利用率降低,某些进程可能长时间无法获得资源(饥饿问题)。

6. 实际系统中的权衡策略

UNIX 和 Windows 的忽略策略:
The Ignoring Strategy in UNIX and Windows:
原因:
◦ 死锁发生的概率较低,且死锁的影响通常可以通过重启进程或系统来解决。
Deadlocks occur infrequently, and their impact can usually be resolved by restarting processes or the system.
◦ 忽略死锁的策略在大多数情况下是可行的,尤其是在用户级应用程序中。
Ignoring deadlocks is feasible in most cases, especially in user-level applications.
权衡:
◦ 这种策略牺牲了部分可靠性以换取更高的性能和简单性。
This strategy sacrifices some reliability for higher performance and simplicity.

高可靠性系统中的检测与恢复:
Detection and Recovery in High-Reliability Systems:
原因:
◦ 在高可靠性系统中,死锁可能导致严重的后果(如系统崩溃或服务中断),因此需要及时检测和恢复。
In high-reliability systems, deadlocks can have serious consequences (e.g., system crashes or service interruptions), so timely detection and recovery are necessary.
权衡:
◦ 检测和恢复过程可能带来额外的开销,但可以显著提高系统的可靠性。
Detection and recovery processes may incur additional overhead but significantly improve system reliability.

资源分配中的动态避免:
Dynamic Avoidance in Resource Allocation:
原因:
◦ 在某些实时系统中,动态避免策略可以确保资源分配的安全性,同时尽量提高资源利用率。
In some real-time systems, dynamic avoidance strategies can ensure the safety of resource allocation while maximizing resource utilization.
权衡:
◦ 动态避免算法的复杂性较高,可能影响系统的实时性能。
Dynamic avoidance algorithms are complex and may affect system real-time performance.


7. 死锁处理的最佳实践

根据系统需求选择合适的策略:
Choose the Right Strategy Based on System Requirements:
• 对于低可靠性系统(如用户级应用程序),可以采用忽略死锁的策略。
For low-reliability systems (e.g., user-level applications), the ignoring strategy is appropriate.
• 对于高可靠性系统(如银行系统、实时系统),应采用检测与恢复或动态避免策略。
For high-reliability systems (e.g., banking systems, real-time systems), detection and recovery or dynamic avoidance strategies should be used.

结合多种策略:
Combine Multiple Strategies:
• 在某些系统中,可以结合忽略、检测与恢复、以及动态避免策略。
In some systems, a combination of ignoring, detection and recovery, and dynamic avoidance strategies can be used.
示例:
◦ 在大多数情况下忽略死锁,但在检测到严重死锁时触发恢复机制。
Example:
◦ Ignore deadlocks most of the time but trigger recovery mechanisms when serious deadlocks are detected.

优化资源分配策略:
Optimize Resource Allocation Strategies:
• 通过合理的资源分配策略(如优先级调度、资源预留等),减少死锁发生的可能性。
Use reasonable resource allocation strategies (e.g., priority scheduling, resource reservation) to reduce the likelihood of deadlocks.


8. 总结

死锁处理的核心在于权衡:
The core of deadlock handling lies in trade-offs:
• 检测与恢复可以提高系统的可靠性,但可能带来额外的开销。
Detection and recovery improve system reliability but may incur additional overhead.
• 动态避免可以预防死锁,但可能降低资源利用率。
Dynamic avoidance prevents deadlocks but may reduce resource utilization.
• 忽略死锁简单高效,但不适用于高可靠性系统。
Ignoring deadlocks is simple and efficient but not suitable for high-reliability systems.

实际系统中,通常根据需求选择合适的策略:
In real systems, appropriate strategies are chosen based on requirements:
• 低可靠性系统:忽略死锁。
Low-reliability systems: Ignore deadlocks.
• 高可靠性系统:检测与恢复或动态避免。
High-reliability systems: Detection and recovery or dynamic avoidance.

最终目标:
The ultimate goal:
• 在性能、可靠性和资源利用率之间找到平衡点。
Find a balance between performance, reliability, and resource utilization.