Ani
unknown
plain_text
5 months ago
3.6 kB
1
Indexable
#include <stdio.h> #include <stdbool.h> #define MAX_P 10 // Maximum number of processes #define MAX_R 10 // Maximum number of resource types // Function to calculate the need matrix void calculateNeed(int need[MAX_P][MAX_R], int max[MAX_P][MAX_R], int alloc[MAX_P][MAX_R], int P, int R) { for (int i = 0; i < P; i++) { for (int j = 0; j < R; j++) { need[i][j] = max[i][j] - alloc[i][j]; } } } // Function to check if the system is in a safe state bool isSafe(int processes[], int avail[], int max[MAX_P][MAX_R], int alloc[MAX_P][MAX_R], int P, int R) { int need[MAX_P][MAX_R]; calculateNeed(need, max, alloc, P, R); bool finish[MAX_P] = {0}; // Initialize all processes as unfinished int safeSeq[MAX_P]; // To store the safe sequence int work[MAX_R]; // Initialize the work array with available resources for (int i = 0; i < R; i++) { work[i] = avail[i]; } int count = 0; while (count < P) { bool found = false; for (int p = 0; p < P; p++) { if (!finish[p]) { // Check if the current process's need can be satisfied bool canAllocate = true; for (int j = 0; j < R; j++) { if (need[p][j] > work[j]) { canAllocate = false; break; } } // If the process can be allocated resources if (canAllocate) { for (int k = 0; k < R; k++) { work[k] += alloc[p][k]; // Simulate resource release } safeSeq[count++] = p; // Add this process to safe sequence finish[p] = true; found = true; } } } // If no process was found in this iteration, system is not in a safe state if (!found) { printf("System is not in a safe state.\n"); return false; } } // If all processes can finish, the system is in a safe state printf("System is in a safe state.\nSafe sequence is: "); for (int i = 0; i < P; i++) { printf("%d ", safeSeq[i]); } printf("\n"); return true; } int main() { int P, R; // Input number of processes and resource types printf("Enter the number of processes: "); scanf("%d", &P); printf("Enter the number of resource types: "); scanf("%d", &R); int processes[MAX_P]; for (int i = 0; i < P; i++) { processes[i] = i; } // Input available instances of resources int avail[MAX_R]; printf("Enter the available instances of each resource:\n"); for (int i = 0; i < R; i++) { scanf("%d", &avail[i]); } // Input maximum demand matrix for each process int max[MAX_P][MAX_R]; printf("Enter the maximum demand of each process for each resource:\n"); for (int i = 0; i < P; i++) { printf("Process %d:\n", i); for (int j = 0; j < R; j++) { scanf("%d", &max[i][j]); } } // Input allocated resources for each process int alloc[MAX_P][MAX_R]; printf("Enter the allocated resources for each process:\n"); for (int i = 0; i < P; i++) { printf("Process %d:\n", i); for (int j = 0; j < R; j++) { scanf("%d", &alloc[i][j]); } } // Check if the system is in a safe state isSafe(processes, avail, max, alloc, P, R); return 0; }
Editor is loading...
Leave a Comment