Deadlock

DeadLock

无论在硬件层面还是软件层面,都有可能出现多device多user的情景,如果不能恰当地分配资源
那么就会发生死锁。在数据库、操作系统中都有类似的问题需要解决。

资源 Resource

包括devices,data records, files。

preemptable and nonpreemptable Resource 可抢占资源与不可抢占资源

首先将资源分为两种:可抢占与不可抢占。可抢占定义为:one that can be taken away from
the process owning it with no ill effects.

在标准PC下,内存是可抢占的,但在不支持swapping或者paging的手机上则不行。

通常,死锁的问题与不可抢占资源有关。

获得资源所需的抽象过程:

  1. 请求资源
  2. 使用资源
  3. 释放资源

如果请求资源时未请求到,则等待。我们之后假设当一个process请求资源被拒绝后,它就
睡过去了。

Resource Acquisition 获取资源

有些资源是需要user process来管理的。其中一种方法是将此与一个信号量相关联。这些信号
量先被初始化为1。互斥量也是同样的道理。

以上三个步骤在信号量中用down表示获取,up表示释放。
如下:

typedef int semaphore
semaphore resource_1;

void process_A(void) {
  down(&resource_1);
  use_resource_1();
  up(^resource_1);
}
typedef int semaphore;
semaphore resource_1;
semaphore resource_2;

void process_A(void) {
  down(&resource_1);
  down(&resource_2);
  //use both resources
  up(&resource_2);
  up(&resource_1);
}

第二段展现了获取多个资源的方式。

现在考虑两个process A and B.

typedef int semaphore;
semaphore resource_1;
semaphore resource_2;

void process_A(void) {
  down(&resource_1);
  down(&resource_2);
  use_both_resource();
  up(&resource_2);
  up(&resource_1);
}

void process_B(void) {
  down(&resource_1);
  down(&resource_2);
  use_both_resource();
  up(&resource_2);
  up(&resource_1);
}
semaphore resource_1;
semaphore resource_2;

void process_A(void) {
  down(&resource_1);
  down(&resource_2);
  use_both_resource();
  up(&resource_2);
  up(&resource_1);
}

void process_B(void) {
    down(&resource_2);
    down(&resource_1);
    use_both_resource();
    up(&resource_1);
    up(&resource_2);
}

第一个表示两进程获取资源的顺序相同,第二个则不同。

Deadlock can be defined formally as follows:

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.

Conditions for resource deadlocks

Four conditions must hold for there to be a resource deadlock:

  1. mutual exclusion condition. Each resourrce is either currently assigned to exactly one process or is available.

  2. Hold-and-wait condition. Processes currently holding resources that were granted earlier can request new resources.

  3. No-preemption condition. Resources previously granted cannot be forcibly taken away from a process.They must be explicitly released by the process holding them.

  4. Circular wait condition.THere must be a circular list of two or more processed, each of which is waiting for a resource held by the next member of the chain.

\

你可能感兴趣的:(Deadlock)