For two non-preemptive resources, if there are two processes, it is possible to generate a deadlock. The process 1 occupies R1, and the R2 is requested, and the process 2 has R2, and the R1 is requested. At this time, a deadlock occurs.
Four conditions in the deadlock:
1.
Mutual exclusion: only one process at a time can use a resource.
2.
Hold and wait: a process holding at least one resource is waiting to acquire additional resources held by other processes.
3.
No preemption: a resource can be released only voluntarily by the process holding it, after that process has completed its task.
4.
Circular wait: there exists a set {P0, P1, …, P0} of waiting processes such that P0 is waiting for a resource that is held by P1, P1is waiting for a resource that is held by P2, …, Pn–1is waiting for a resource that is held by Pn, and P0is waiting for a resource that is held by P0.
Avoid dead locks:
Destroy the "non-preemptive" condition: When a process cannot get the required resources, it is in a waiting state. During the waiting period, the resource he posted will be implicitly released to the system's resource list, that is, the process 1 releases the original possession R1, the process 2 releases the original occupied R2. Can be used by other processes, while the waiting process can only re-enable its original resources and new applications can restart, execute.
semaphore resouce_1
samaphore resouce_2
void process_1(void){
down(&resouce_1);
down(&resouce_2);
use_both_resouces();
up(&resouce_2);
up(&resouce_1);
}
void process_2(void){
down(&resouce_2);
down(&resouce_1);
use_both_resouces();
up(&resouce_1);
up(&resouce_2);
}