fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int main() {
  5. // your code goes here
  6. return 0;
  7. }
Success #stdin #stdout 0s 5328KB
stdin
// Simplified C Program to Simulate Safety Check (Deadlock Avoidance)

#include <stdio.h>
#include <stdbool.h>

// Function to simulate the Safety Algorithm
bool isSafe(int available[], int max[][3], int allocation[][3], int P, int R) {
    int work[R]; // A copy of available resources
    for (int i = 0; i < R; i++) {
        work[i] = available[i];
    }
    
    bool finish[P]; // Tracks if a process can finish
    for (int i = 0; i < P; i++) {
        finish[i] = false;
    }
    
    int need[P][R];
    // Calculate Need matrix
    for (int i = 0; i < P; i++) {
        for (int j = 0; j < R; j++) {
            need[i][j] = max[i][j] - allocation[i][j];
        }
    }

    int safe_sequence[P];
    int count = 0;

    // The main safety check loop
    while (count < P) {
        bool found = false;
        // Find a process i that is not finished AND (need <= work)
        for (int i = 0; i < P; i++) {
            if (finish[i] == false) {
                int j;
                for (j = 0; j < R; j++) {
                    if (need[i][j] > work[j]) { // Process i's need is not met
                        break;
                    }
                }
                
                if (j == R) { // Process i's need is met (j went through all resources)
                    // Grant resources and simulate process finish
                    for (int k = 0; k < R; k++) {
                        work[k] += allocation[i][k];
                    }
                    safe_sequence[count++] = i;
                    finish[i] = true;
                    found = true;
                }
            }
        }
        
        if (found == false) { // No process could run in this iteration
            return false; // System is in an UNSAFE state
        }
    }

    // System is in a SAFE state
    printf("System is in a SAFE state. Safe sequence: ");
    for (int i = 0; i < P; i++) {
        printf("P%d ", safe_sequence[i]);
    }
    printf("\n");
    return true;
}

// Example usage would define P (processes), R (resources), and the matrices.
// 
stdout
Standard output is empty