Skip to content

Instantly share code, notes, and snippets.

@GiovanniMounir
Created April 20, 2019 20:18
Show Gist options
  • Save GiovanniMounir/32196c1cfb5873f49618ecbdf4c68a24 to your computer and use it in GitHub Desktop.
Save GiovanniMounir/32196c1cfb5873f49618ecbdf4c68a24 to your computer and use it in GitHub Desktop.
Banker's algorithm for OS (Safety Algorithm; C++)
/*
CLI output inspired by https://gist.github.com/Dammonoit/a77154b7bc688ef25298be79b5ea99fb (@Dammonoit on GitHub)
Safety criteria logic from https://www.geeksforgeeks.org/program-bankers-algorithm-set-1-safety-algorithm/
*/
#include <stdio.h>
int **initialize2D(int n, int m)
{
int **_A = new int *[n];
for (int i = 0; i < n; ++i)
_A[i] = new int[m];
return _A;
}
int main()
{
int n, m, i, j;
printf("Number of resources: ");
scanf("%d", &m);
int *AVAILABLE = new int[m];
printf("Available instances of each resource: \n");
for (i = 0; i < m; i++)
{
printf("%c: ", (i + 97));
scanf("%d", &AVAILABLE[i]);
}
printf("Number of processes: ");
scanf("%d", &n);
int *finish = new int[n]; //Used later to detemrine whether the system is in safe or unsafe state
int **MAX = initialize2D(n, m);
int **ALLOCATED = initialize2D(n, m);
int **NEED = initialize2D(n, m);
printf("Enter the allocation matrix:\n ");
for (i = 0; i < m; i++)
printf(" %c", (i + 97));
printf("\n");
for (i = 0; i < n; i++)
{
finish[i] = 0; //Initialize finish
printf("P[%d] ", i);
for (j = 0; j < m; j++)
{
scanf("%d", &ALLOCATED[i][j]);
}
}
printf("Enter the MAX matrix:\n ");
for (i = 0; i < m; i++)
{
printf(" %c", (i + 97));
}
printf("\n");
for (i = 0; i < n; i++)
{
printf("P[%d] ", i);
for (j = 0; j < m; j++)
scanf("%d", &MAX[i][j]);
}
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
NEED[i][j] = MAX[i][j] - ALLOCATED[i][j];
}
int count = 0;
int *seq = new int[n];
//We should make a copy of AVAILABLE as "WORK" so that we do not modify the entered values,
//but it does not matter in this scenario as the application will exit after finding the results.
while (count < n)
{
bool found = false;
for (i = 0; i < n; i++)
{
if (finish[i] == 0)
{
for (j = 0; j < m; j++)
if (NEED[i][j] > AVAILABLE[j])
break; //Need cannot be satisfied
if (j == m)
{
//Needs satisfied; process is going to terminate:
for (int k = 0; k < m; k++)
AVAILABLE[k] += ALLOCATED[i][k]; //Free resources
seq[count++] = i;
finish[i] = 1;
found = true;
//Process terminated
}
}
}
if (found == false)
{
printf("System is not in safe state");
return 0;
}
}
printf("Safe sequence:\n[");
for (int i = 0; i < n; i++)
printf("P[%d], ", seq[i]);
printf("\b\b]"); //Remove last ,
//make sure to execute delete[] on the above array pointers in production
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment