Bankers Algo - Os Lab

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 7

Bankers algo

// Java program to illustrate Banker's Algorithm 
import java.util.*; 

class GFG 

// Number of processes 
static int P = 5; 

// Number of resources 
static int R = 3; 

// Function to find the need of each process 
static void calculateNeed(int need[][], int maxm[][], 
                int allot[][]) 

    // Calculating Need of each P 
    for (int i = 0 ; i < P ; i++) 
        for (int j = 0 ; j < R ; j++) 

            // Need of instance = maxm instance - 
            //               allocated instance 
            need[i][j] = maxm[i][j] - allot[i][j]; 

// Function to find the system is in safe state or not 
static boolean isSafe(int processes[], int avail[], int maxm[][], 
            int allot[][]) 

    int [][]need = new int[P][R]; 

    // Function to calculate need matrix 
    calculateNeed(need, maxm, allot); 

    // Mark all processes as infinish 
    boolean []finish = new boolean[P]; 

    // To store safe sequence 
    int []safeSeq = new int[P]; 

    // Make a copy of available resources 
    int []work = new int[R]; 
    for (int i = 0; i < R ; i++) 
        work[i] = avail[i]; 

    // While all processes are not finished 
    // or system is not in safe state. 
    int count = 0; 
    while (count < P) 
    { 
        // Find a process which is not finish and 
        // whose needs can be satisfied with current 
        // work[] resources. 
        boolean found = false; 
        for (int p = 0; p < P; p++) 
        { 
            // First check if a process is finished, 
            // if no, go for next condition 
            if (finish[p] == false) 
            { 
                // Check if for all resources of 
                // current P need is less 
                // than work 
                int j; 
                for (j = 0; j < R; j++) 
                    if (need[p][j] > work[j]) 
                        break; 

                // If all needs of p were satisfied. 
                if (j == R) 
                { 
                    // Add the allocated resources of 
                    // current P to the available/work 
                    // resources i.e.free the resources 
                    for (int k = 0 ; k < R ; k++) 
                        work[k] += allot[p][k]; 

                    // Add this process to safe sequence. 
                    safeSeq[count++] = p; 

                    // Mark this p as finished 
                    finish[p] = true; 

                    found = true; 
                } 
            } 
        } 

        // If we could not find a next process in safe 
        // sequence. 
        if (found == false) 
        { 
            System.out.print("System is not in safe state"); 
            return false; 
        } 
    } 

    // If system is in safe state then 
    // safe sequence will be as below 
    System.out.print("System is in safe state.\nSafe"
        +" sequence is: "); 
    for (int i = 0; i < P ; i++) 
        System.out.print(safeSeq[i] + " "); 

    return true; 

// Driver code 
public static void main(String[] args) 

    int processes[] = {0, 1, 2, 3, 4}; 
    // Available instances of resources 
    int avail[] = {3, 3, 2}; 

    // Maximum R that can be allocated 
    // to processes 
    int maxm[][] = {{7, 5, 3}, 
                    {3, 2, 2}, 
                    {9, 0, 2}, 
                    {2, 2, 2}, 
                    {4, 3, 3}}; 

    // Resources allocated to processes 
    int allot[][] = {{0, 1, 0}, 
                    {2, 0, 0}, 
                    {3, 0, 2}, 
                    {2, 1, 1}, 
                    {0, 0, 2}}; 

    // Check system is in safe state or not 
    isSafe(processes, avail, maxm, allot); 

Output:

Banker algorithm ex2

// A Multithreaded Program that implements the banker's algorithm.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <stdbool.h>
#include <time.h>

int nResources,
nProcesses;
int *resources;
int **allocated;
int **maxRequired;
int **need;
int *safeSeq;
int nProcessRan = 0;

pthread_mutex_t lockResources;
pthread_cond_t condition;

// get safe sequence is there is one else return false


bool getSafeSeq();
// process function
void* processCode(void* );

int main(int argc, char** argv) {


srand(time(NULL));

printf("\nNumber of processes? ");


scanf("%d", &nProcesses);

printf("\nNumber of resources? ");


scanf("%d", &nResources);

resources = (int *)malloc(nResources * sizeof(*resources));


printf("\nCurrently Available resources (R1 R2 ...)? ");
for(int i=0; i<nResources; i++)
scanf("%d", &resources[i]);

allocated = (int **)malloc(nProcesses * sizeof(*allocated));


for(int i=0; i<nProcesses; i++)
allocated[i] = (int *)malloc(nResources * sizeof(**allocated));

maxRequired = (int **)malloc(nProcesses * sizeof(*maxRequired));


for(int i=0; i<nProcesses; i++)
maxRequired[i] = (int *)malloc(nResources *
sizeof(**maxRequired));

// allocated
printf("\n");
for(int i=0; i<nProcesses; i++) {
printf("\nResource allocated to process %d (R1 R2 ...)? ", i+1);
for(int j=0; j<nResources; j++)
scanf("%d", &allocated[i][j]);
}
printf("\n");

// maximum required resources


for(int i=0; i<nProcesses; i++) {
printf("\nMaximum resource required by process %d (R1 R2 ...)? ",
i+1);
for(int j=0; j<nResources; j++)
scanf("%d", &maxRequired[i][j]);
}
printf("\n");

// calculate need matrix


need = (int **)malloc(nProcesses * sizeof(*need));
for(int i=0; i<nProcesses; i++)
need[i] = (int *)malloc(nResources * sizeof(**need));

for(int i=0; i<nProcesses; i++)


for(int j=0; j<nResources; j++)
need[i][j] = maxRequired[i][j] - allocated[i][j];

// get safe sequence


safeSeq = (int *)malloc(nProcesses * sizeof(*safeSeq));
for(int i=0; i<nProcesses; i++) safeSeq[i] = -1;

if(!getSafeSeq()) {
printf("\nUnsafe State! The processes leads the system to a unsafe
state.\n\n");
exit(-1);
}

printf("\n\nSafe Sequence Found : ");


for(int i=0; i<nProcesses; i++) {
printf("%-3d", safeSeq[i]+1);
}

printf("\nExecuting Processes...\n\n");
sleep(1);

// run threads
pthread_t processes[nProcesses];
pthread_attr_t attr;
pthread_attr_init(&attr);

int processNumber[nProcesses];
for(int i=0; i<nProcesses; i++) processNumber[i] = i;

for(int i=0; i<nProcesses; i++)


pthread_create(&processes[i], &attr, processCode, (void *)
(&processNumber[i]));

for(int i=0; i<nProcesses; i++)


pthread_join(processes[i], NULL);

printf("\nAll Processes Finished\n");

// free resources
free(resources);
for(int i=0; i<nProcesses; i++) {
free(allocated[i]);
free(maxRequired[i]);
free(need[i]);
}
free(allocated);
free(maxRequired);
free(need);
free(safeSeq);
}

bool getSafeSeq() {
// get safe sequence
int tempRes[nResources];
for(int i=0; i<nResources; i++) tempRes[i] = resources[i];

bool finished[nProcesses];
for(int i=0; i<nProcesses; i++) finished[i] = false;
int nfinished=0;
while(nfinished < nProcesses) {
bool safe = false;

for(int i=0; i<nProcesses; i++) {


if(!finished[i]) {
bool possible = true;
for(int j=0; j<nResources; j++)
if(need[i][j] > tempRes[j]) {
possible = false;
break;
}

if(possible) {
for(int j=0; j<nResources; j++)
tempRes[j] += allocated[i][j];
safeSeq[nfinished] = i;
finished[i] = true;
++nfinished;
safe = true;
}
}
}

if(!safe) {
for(int k=0; k<nProcesses; k++) safeSeq[k] = -1;
return false; // no safe sequence found
}
}
return true; // safe sequence found
}

// process code
void* processCode(void *arg) {
int p = *((int *) arg);

// lock resources
pthread_mutex_lock(&lockResources);

// condition check
while(p != safeSeq[nProcessRan])
pthread_cond_wait(&condition, &lockResources);

// process
printf("\n--> Process %d", p+1);
printf("\n\tAllocated : ");
for(int i=0; i<nResources; i++)
printf("%3d", allocated[p][i]);

printf("\n\tNeeded : ");
for(int i=0; i<nResources; i++)
printf("%3d", need[p][i]);

printf("\n\tAvailable : ");
for(int i=0; i<nResources; i++)
printf("%3d", resources[i]);

printf("\n"); sleep(1);

printf("\tResource Allocated!");
printf("\n"); sleep(1);
printf("\tProcess Code Running...");
printf("\n"); sleep(rand()%3 + 2); // process code
printf("\tProcess Code Completed...");
printf("\n"); sleep(1);
printf("\tProcess Releasing Resource...");
printf("\n"); sleep(1);
printf("\tResource Released!");

for(int i=0; i<nResources; i++)


resources[i] += allocated[p][i];

printf("\n\tNow Available : ");


for(int i=0; i<nResources; i++)
printf("%3d", resources[i]);
printf("\n\n");

sleep(1);

// condition broadcast
nProcessRan++;
pthread_cond_broadcast(&condition);
pthread_mutex_unlock(&lockResources);
pthread_exit(NULL);
}

You might also like