×

Deadlock Detection Program in C

What is Deadlock?

A deadlock is a circumstance where a group in the process is halted because they are each holding onto resources while waiting for other methods to obtain them.

Think of a situation where only one track and two trains are approaching each other. Once they are in front of each other, none of the trains can move. When multiple processes are waiting for resources owned by other methods, a similar situation arises in operating systems.

There is a deadlock in an operating system when a process or thread enters a waiting state because another waiting process is holding a system resource requested by another method.

Almost all locking-based applications have the potential to deadlock. The Berkeley DB Concurrent Data Store product, which assures deadlock-free operation at the expense of decreased concurrency, or situations where all the threads of control accessing the database are read-only, are the exceptions to this rule.

Deadlock-free data access patterns exist (for instance, when an application overwrites fixed-length records in an existing database), but they are incredibly uncommon.

The deadlock detector locates deadlocks by scanning the "waits-for" graph for a cycle. To be more exact, the deadlock detector scans the lock table and examines each lock object that is locked at the moment. Each object contains lockers now closed to it and a list of vaults awaiting a lock. A partial ordering is defined by the list of waiting lockers for each object. Every holding locker must release its lock before a waiting locker can go forward, so for a specific thing, every holding locker comes after every waiting locker. Conceptually, the partial orderings are topologically sorted once each object has been studied. If this topological sort reveals any cycles, the lockers composing the cycle are stuck in an impasse. The safe chosen for rejection is one of the others.

Conditions for Deadlock

  • Mutual exclusion: Only one process may hold a resource at once. Put another way, if a process P1 uses a resource R at a specific moment, another process P2 cannot have the same resource R at that exact moment. The resource R is available to process P2, but process P1 cannot use it concurrently with process P2.
  • Hold & Wait: A process might request other resources that are being held by another method while simultaneously having several resources of its own. For instance, a process P1 might be saving two resources, R1 and R2, and it might also be requesting some resource R3 that process P2 is now having.
  • Preemption is not permitted: A resource cannot be forcibly removed from the process by another process. For instance, if process P1 utilizes resource R, process P2 cannot completely grab that resource. If that is the case, different scheduling algorithms are not necessary. Process P2 has can ask for the resource R and waits for the process P1 to release it.
  • Circular Wait: A circular wait is a situation in which a first process is waiting for a resource held by a second process, a second process is waiting for a third process's help, and so on. The final process is now waiting for the resist process’s resources result; the method is releasing its resource; instead, everyone is waiting for the processor to remove techniques.

Deadlock Avoidance

The OS can avoid deadlock by using deadlock avoidance techniques. Before bee execution, the OS will track the maximum resources needed for a process during its entire life cycle. Before allocating any newly requested resource to any procedure, the OS will continuously check the system’s state.

In essence, the OS will strive to avoid entering a cyclic wait condition during the deadlock avoidance.

Suppose the system’s subsequent state results in a deadlock, the request for any resource will be granted in deadlock avoidance.

The process should specify the maximum number of resources of each type it may ever require, according to the simplest and most practical way. There can never be a cyclic wait condition thanks to the deadlock avoidance algorithm's examination of the resource allocations.

Deadlock Detection

With this approach, the OS anticipates a deadlock in the future. As a result, it periodically executes a deadlock detection algorithm, and upon detecting a dead draw initiates a recovery strategy.

The OS's primary responsibility is to find the deadlock. There are two ways to detect.

Deadlock detection can cause deadlocks. Then check the state of the system to see if a deadlock has occurred and fix it. Algorithms are used to track resource allocations and process state, roll back, restart one or more processes, and eliminate detected deadlocks. Because the operating system's resource scheduler knows what resources each process has locked or is currently requesting, it's easy to detect deadlocks that have already occurred.

FOR A SINGLE INSTANCE OF EVERY RESOURCE

The OS monitors the creation of a circle in the wait-for-graph approach. With certain variations, it is somewhat similar to the resource allocation graph (RAG). Most often, it confuses the Wait-for graph and RAG.

FOR MULTIPLE INSTANCES OF EVERY RESOURCE

We adopt the Safety algorithm, which follows the same methodology as the Banker's algorithm, for resources with many instances. However, there is no maximum necessary resource matrix. Allocated, available, and current requirement matrices are the only ones present.

DEADLOCK AVOIDANCE ALGORITHM (BANKERS ALGORITHM)

Steps of Algorithm

Step 1

  1. Let Work(vector) length = m
  2. Finish(vector) length = n
  3. Initialise Work= Available.
    1. if Allocationi = 0 ∀ i ∈[0,N-1], then Finish[i] = true; 
      otherwise, Finish[i]= false.

Step 2

  1. Find an index i such that both
    1. Finish[i] == false
    1. Work >= Request i
      If there exists no i, go to stepI4.

Step 3

  1. Work += Allocation i
  2. Finish[i] = true
    Go to Step 2.

Step 4

  1. For some i in [0, N), if Finish[i]==false, then the system is considered deadlock Finish [i]==false the, process Pi is deadlocked.

DEADLOCK DETECTION PROGRAM

#include<stdio.h>
static int mark[20];
int i, j, np, nr;


int main()
{
int alloc[10][10],request[10][10],avail[10],r[10],w[10];


printf ("\nEnter the no of the process: ");
scanf("%d",&np);
printf ("\nEnter the no of resources: ");
scanf("%d",&nr);
for(i=0;i<nr; i++)
{
printf("\nTotal Amount of the Resource R % d: ",i+1);
scanf("%d, &r[i]);
}
printf("\nEnter the request matrix:");


for(i=0;i<np;i++)
for(j=0;j<nr;j++)
scanf("%d",&request[i][j]);


printf("\nEnter the allocation matrix:");
for(i=0;i<np;i++)
for(j=0;j<nr;j++)
scanf("%d",&alloc[i][j]);
/*Available Resource calculation*/
for(j=0;j<nr;j++)
{
avail[j]=r[j];
for(i=0;i<np;i++)
{
avail[j]-=alloc[i][j];


}
}


//marking processes with zero allocation


for(i=0;i<np;i++)
{
int count=0;
 for(j=0;j<nr;j++)
   {
      if(alloc[i][j]==0)
        count++;
      else
        break;
    }
 if(count==nr)
 mark[i]=1;
}
// initialize W with avail


for(j=0;j<nr; j++)
    w[j]=avail[j];


//mark processes with request less than or equal to W
for(i=0;i<np; i++)
{
int canbeprocessed= 0;
 if(mark[i]!=1)
{
   for(j=0;j<nr;j++)
    {
      if(request[i][j]<=w[j])
        canbeprocessed=1;
      else
         {
         canbeprocessed=0;
         break;
          }
     }
if(canbeprocessed)
{
mark[i]=1;


for(j=0;j<nr;j++)
w[j]+=alloc[i][j];
}
}
}


//checking for unmarked processes
int deadlock=0;
for(i=0;i<np;i++)
if(mark[i]!=1)
deadlock=1;




if(deadlock)
printf("\n Deadlock detected");
else
printf("\n No Deadlock possible");
}
Deadlock Detection Program in C

Related Topics

C Program of Fencing the Ground

The college's ground is rectangular. Fencing the ground the management makes the decision to construct a fence around the ground. They planned to wrap a thick rope around the ground...

1 minute read.

Nested Structure in C

In C language, we can create nested Structure (Structure within Structure). There are two ways to define a nested structure. By separate structure By Embedded structure   Separate structure In a separate...

1 minute read.

function pointer as argument in C

Pointers are considered difficult to understand for beginners but pointers can be made to work if you fiddle with them long enough. So, let’s understand this step by step. What are...

3 minutes read.

Long int in C

We use data type to avoid the type of data to be stored for a variable at the time of declaration.So, we can say that the variable type is known...

3 minutes read.

First Fit Program in C

This is one of the easiest ways to allocate memory. The main goal is to divide the memory into several fixed sizes. In C, there is only one process for...

3 minutes read.

While Loop Syntax in C

What is Loop? The statements in the sequence are repeatedly executed via looping statements in C until the condition is met. The body of a loop and a control statement make...

4 minutes read.

Entry Control Loop in C

Initially, an entry control loop verifies the termination condition at the entry point. After that, its control passes to the main body of the while or for loop if the...

3 minutes read.

Explain the Increment and Decrement Operators in C

In the C programming language, the increment operator (++) and the decrement operator (--) are used to increase or decreasing a variable’s value by 1, respectively. The increment operator is written...

10 minutes read.

Int in C

The keyword int in C programming stands for integer and it is a data type which is used for variable declarations or declaration of functions of different types. Similar to...

4 minutes read.

Error handling in C

Error handling in C: The C programming standard does not provide direct convenience for handling the errors. However, being a system programming language, it definitely will give access to handling...

4 minutes read.

For Loop in C Programming Examples

The Syntax of the For Loop for (initialization statement; termination condition; modifying (increment/ decrement) statement) {       /* main body of the For loop */     } In for loop, the initialization command...

6 minutes read.

Garbage in C

Garbage in C The C programming language is a perfect fit for embedded systems as it provides low level control, structured programming, and portability. On the contrary, it does not provide...

3 minutes read.

Fibonacci series in C

We have learned about the Fibonacci series in mathematics. For a quick recap, A Fibonacci series is the sequence of numbers following a certain pattern i.e., the next number should...

3 minutes read.

memcpy() in C

Introduction: Here we discuss about the memcpy() function in C. The memcpy() function is also called the Copy Memory Block function. Used to create a copy of a specific drawing...

4 minutes read.

abs() function in C

abs() function is a built-in function present in the stdlib.h header file. It returns an integer value. abs() function converts a negative value into a positive value. For example, if...

4 minutes read.

Type qualifiers in C

Type qualifiers in C: In the C programming language, type qualifiers are the keywords that prepend to the variables to change their accessibility, i.e., we can tell that the type...

4 minutes read.

C program to find factorial of a number using Recursion

What does the term "Factorial of a Number" mean? In mathematics, factorial is the product of all positive integers that are less than or equal to a certain positive integer, and...

2 minutes read.

Random function in C

Random function in C In the C programming language, the rand() is a function used for Pseudo Random Number Generator (PRNG). The random number generated by the rand() function is not...

4 minutes read.

Library Functions in C

What are library functions? Library functions are the built-in functions (functions provided by the system) which are stored in the library. The library is the common location where these functions are...

3 minutes read.

Type Casting in C

Type casting is a way to convert a variable from one data type to another data type.Syntax: (type) expression;     Example: #include <stdio.h> int main() { int a,b; float sum; printf("Example of Type Casting\n"); printf("Enter any integer nos:"); scanf("%d",&a,&b); sum=a+b; printf("Sum: %f",sum); return 0; } Output Example...

1 minute read.