×

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

For loop in C Programming

In the C programming language, the for loop is used to repeatedly iterate over a set of instructions or a section of code. It is frequently used to traverse array-based...

3 minutes read.

Calloc in C

The calloc() is a library function in C which is used for memory allocation. The calloc() function dynamically allocates multiple blocks of memory to complex data structures. This includes data structures...

3 minutes read.

Multiplication table program in C using For loop

Before we move on the program of multiplication table of any natural number, first we have to know about the For loop statement. The syntax of ‘for’ loop in C programming...

3 minutes read.

OpenGL in C

OpenGL stands for Open Graphics Library. It is a low-level, widely supported modeling and rendering software package that is widely available across all the platforms. It is an API used...

4 minutes read.

Simple hash() function in C

Introduction In this context, we briefly discuss HASH FUNCTION, HASHING or HASH TABLE in C. It is a function used to map data and mapped arbitrary sizes to the fixed-size values. The...

7 minutes read.

Array to function in C

Array to function in C We can create functions that receive an array as an argument. To pass an array into a function, we need to write the name of the...

4 minutes read.

How to install a C compiler in windows 10-64bit

Many C compilers can be installed on your pc. The most downloaded compilers include GCC, Turbo C++, Visual Studio, etc. This article includes the installation of the Turbo C++ compiler in...

6 minutes read.

Assignment Operator Program in C

An assignment operator is a symbol used to assign a value to a variable in a programming language. The assignment operator is often the equal symbol (=) in programming languages....

12 minutes read.

Classification of Programming language

 Classification of Programming language  The programming language represents a set of instructions compiled along with each other to perform a specific task provided by the CPU (Central Processing Unit). A programming...

3 minutes read.

7 Best IDEs for C/C++ Developers in 2024

As we all know that in programming languages, C is known as the building block which cannot be contradicted, and C++ is the prolong kind of C and it can...

4 minutes read.

Hexadecimal to Binary in C

What is hexadecimal? Hexadecimal defines a sequence of numbers centered on-16, i.e., before assigning the next number to a new location, it describes a numbering scheme that includes 16 sequential numbers as basic...

2 minutes read.

Kruskal algorithm in C

Given a weighted graph, Kruskal's algorithm generates a spanning tree with the lowest possible weights. Start by creating an edge list for the given graph, including the weights. Sort the...

3 minutes read.

Write() function in c

As the name suggests the write () function is used to write the file descriptor. In other words it is used to write any file name without specifying file name,...

3 minutes read.

While-Loop in C

Syntax of While Loop The syntax that has been used for the while loop in C programming language is: while (termination condition) {   // the body of the loop  } Working of While-Loop Initially, we...

3 minutes read.

Builtin functions of GCC compiler

Certain built-in functions are present in the GCC compiler. These features are as follows: Function_ built in_popcount (x) The number of 1s in data of the integer type can be counted using...

3 minutes read.

Bar3d() function in C Graphics

The bar3d function is used to create a 2-dimensional filled-in rectangular bar. We can also create three-dimensional shapes in C using helpful function. The first step in creating this 3D...

3 minutes read.

Call by Value and Call by Reference in C

Call by reference and call by value are two different ways of passing arguments to a function in C programming language. Call by reference means that the called function is...

4 minutes read.

How to use sine() function in C

What is Function? The function is a set of statements. It takes input and performs some computation to produce output. The process is a set of codes only achieved when it is...

3 minutes read.

Bit Stuffing Program in C

What is a Bit Stuffing? The process of inserting one or more extra bits (0) into data is known as bit stuffing. To provide signalling information to a recipient, these are...

3 minutes read.

Recursion in C

Recursion is a programming technique that allows the programmer to call the function within the same function. The function which calls the same function is known as recursive function but a...

1 minute read.