OneCompiler

os5

101

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

#define MAX_PROCESSES 10
#define MAX_RESOURCES 10

int allocation[MAX_PROCESSES][MAX_RESOURCES];
int max[MAX_PROCESSES][MAX_RESOURCES];
int need[MAX_PROCESSES][MAX_RESOURCES];
int available[MAX_RESOURCES];

void calculateNeed(int m, int n) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
need[i][j] = max[i][j] - allocation[i][j];
}
}
}

bool checkRequest(int m, int n, int process, int *request) {
for (int i = 0; i < n; i++) {
if (request[i] > need[process][i] || request[i] > available[i]) {
return false;
}
}
return true;
}

int main() {
int m, n;

printf("Enter number of processes: ");
scanf("%d", &m);
printf("Enter number of resource types: ");
scanf("%d", &n);

printf("Enter available instances of each resource type: ");
for (int i = 0; i < n; i++) {
    scanf("%d", &available[i]);
}

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

printf("Enter maximum requirement matrix:\n");
for (int i = 0; i < m; i++) {
    for (int j = 0; j < n; j++) {
        scanf("%d", &max[i][j]);
    }
}

calculateNeed(m, n);

printf("Need Matrix:\n");
for (int i = 0; i < m; i++) {
    printf("P%d: ", i);
    for (int j = 0; j < n; j++) {
        printf("%d ", need[i][j]);
    }
    printf("\n");
}

int process;
printf("Enter process requesting resources: ");
scanf("%d", &process);

int request[MAX_RESOURCES];
printf("Enter the request for process P%d: ", process);
for (int i = 0; i < n; i++) {
    scanf("%d", &request[i]);
}

if (checkRequest(m, n, process, request)) {
    printf("Request can be granted immediately.\n");
} else {
    printf("Request cannot be granted immediately.\n");
}

return 0;

}
Q2)
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>

#define ARRAY_SIZE 1000

int main() {
int rank, size;
int array[ARRAY_SIZE];
int local_max, global_max;

MPI_Init(NULL, NULL);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);

if (rank == 0) {
    // Generate random numbers
    for (int i = 0; i < ARRAY_SIZE; i++) {
        array[i] = rand() % 1000;
    }
}

// Scatter the array to all processes
MPI_Scatter(array, ARRAY_SIZE / size, MPI_INT, array, ARRAY_SIZE / size, MPI_INT, 0, MPI_COMM_WORLD);

// Find local max
local_max = array[0];
for (int i = 1; i < ARRAY_SIZE / size; i++) {
    if (array[i] > local_max) {
        local_max = array[i];
    }
}

// Find global max
MPI_Reduce(&local_max, &global_max, 1, MPI_INT, MPI_MAX, 0, MPI_COMM_WORLD);

if (rank == 0) {
    printf("Max number: %d\n", global_max);
}

MPI_Finalize();

return 0;

}