Animesh

 avatar
unknown
plain_text
5 months ago
2.8 kB
1
Indexable
#include <stdio.h>
#include <stdbool.h>

#define P 5  // Number of processes
#define R 3  // Number of resource types

// Function to calculate the need matrix
void calculateNeed(int need[P][R], int max[P][R], int alloc[P][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[P][R], int alloc[P][R]) {
    int need[P][R];
    calculateNeed(need, max, alloc);
    
    bool finish[P] = {0};   // Initialize all processes as unfinished
    int safeSeq[P];         // To store the safe sequence
    int work[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 processes[P] = {0, 1, 2, 3, 4};

    // Available instances of resources
    int avail[R] = {3, 3, 2};

    // Maximum resources each process may need
    int max[P][R] = {{7, 5, 3},
                     {3, 2, 2},
                     {9, 0, 2},
                     {2, 2, 2},
                     {4, 3, 3}};

    // Resources allocated to each process
    int alloc[P][R] = {{0, 1, 0},
                       {2, 0, 0},
                       {3, 0, 2},
                       {2, 1, 1},
                       {0, 0, 2}};

    // Check if the system is in a safe state
    isSafe(processes, avail, max, alloc);

    return 0;
}
Editor is loading...
Leave a Comment