0% found this document useful (0 votes)
16 views

Deadlock Detection Algorithm

Uploaded by

stickman8068
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Deadlock Detection Algorithm

Uploaded by

stickman8068
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <stdio.

h>

#define MAX_PROCESSES 10
#define MAX_RESOURCES 10

int allocation[MAX_PROCESSES][MAX_RESOURCES];
int request[MAX_PROCESSES][MAX_RESOURCES];
int available[MAX_RESOURCES];
int work[MAX_RESOURCES];
int marked[MAX_PROCESSES]; // 1 if process is finished
int safe_sequence[MAX_PROCESSES];

int main() {
int num_processes, num_resources;

// Get the number of processes and resources


printf("Enter the number of processes: ");
scanf("%d", &num_processes);
printf("Enter the number of resources: ");
scanf("%d", &num_resources);

// Input the available resources


printf("Enter the available resources:\n");
for (int i = 0; i < num_resources; i++) {
printf("Resource R%d: ", i + 1);
scanf("%d", &available[i]);
}

// Input the allocation matrix


printf("Enter the allocation matrix:\n");
for (int i = 0; i < num_processes; i++) {
for (int j = 0; j < num_resources; j++) {
scanf("%d", &allocation[i][j]);
}
}

// Input the request matrix


printf("Enter the request matrix:\n");
for (int i = 0; i < num_processes; i++) {
for (int j = 0; j < num_resources; j++) {
scanf("%d", &request[i][j]);
}
}

// Step 1: Initialize work and marked arrays


for (int i = 0; i < num_resources; i++) {
work[i] = available[i];
}
for (int i = 0; i < num_processes; i++) {
marked[i] = 0;
}

// Step 2: Find a safe sequence


int count = 0; // Count of processes that can finish
for (int k = 0; k < num_processes; k++) {
for (int i = 0; i < num_processes; i++) {
if (marked[i] == 0) { // If process is not marked yet
int can_be_processed = 1;
// Check if process's requests can be satisfied
for (int j = 0; j < num_resources; j++) {
if (request[i][j] > work[j]) {
can_be_processed = 0;
break;
}
}
// If the process can be satisfied, mark it and release its resources
if (can_be_processed) {
safe_sequence[count++] = i;
marked[i] = 1; // Mark the process as completed
// Release resources allocated to the process
for (int j = 0; j < num_resources; j++) {
work[j] += allocation[i][j];
}
}
}
}
}

// Step 3: Check if all processes could finish


if (count == num_processes) {
printf("System is in a safe state.\n");
printf("Safe sequence: ");
for (int i = 0; i < num_processes; i++) {
printf("P%d ", safe_sequence[i]);
}
printf("\n");
} else {
printf("Deadlock detected. No safe sequence found.\n");
}

return 0;
}

You might also like