PRACTICAL NO.
11
Deadlock Avoidance Banker’s Algorithm
Objectives: PLO CLO LL
The objective of this practical is to implement the Banker’s 5 2 P4
Algorithm for deadlock avoidance using C++. The Banker’s
Algorithm is used in operating systems to safely allocate resources to processes when multiple
instances of each resource are available. It ensures that the system remains in a safe state and
avoids deadlocks.
Implementation:
You will write a C++ program that:
• Stores the allocation, maximum demand, and available resources.
• Computes the need matrix.
• Applies the Banker’s Algorithm to determine whether a safe sequence exists.
• Prints the safe execution sequence if the system is in a safe state.
C++ Program – Banker’s Algorithm
Banker's Algorithm in C++
#include <iostream>
using namespace std;
int main() {
// Number of processes
const int n = 5;
// Number of resource types
const int m = 3;
// Allocation Matrix
int alloc[n][m] = {
{0, 1, 0}, // P0
{2, 0, 0}, // P1
{3, 0, 2}, // P2
{2, 1, 1}, // P3
{0, 0, 2} // P4
};
// Maximum demand matrix
int max[n][m] = {
{7, 5, 3}, // P0
{3, 2, 2}, // P1
{9, 0, 2}, // P2
{2, 2, 2}, // P3
{4, 3, 3} // P4
};
// Available resources
int avail[m] = {3, 3, 2};
// To mark completed processes
int f[n] = {0};
// Safe sequence
int ans[n], ind = 0;
// Need matrix
int need[n][m];
// Calculate the need matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
need[i][j] = max[i][j] - alloc[i][j];
}
}
// Apply Banker's Algorithm
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
if (f[i] == 0) {
bool flag = false;
for (int j = 0; j < m; j++) {
if (need[i][j] > avail[j]) {
flag = true;
break;
}
}
// If process i can be allocated resources
if (!flag) {
ans[ind++] = i;
for (int y = 0; y < m; y++) {
avail[y] += alloc[i][y];
}
f[i] = 1;
}
}
}
}
// Print the safe sequence
cout << "Following is the SAFE Sequence:" << endl;
for (int i = 0; i < n - 1; i++) {
cout << "P" << ans[i] << " -> ";
}
cout << "P" << ans[n - 1];
return 0;
}
CONCLUSION:
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
RUBRICS:
Performance & Lab Report
Description Total Marks Obtained
Marks
Coding Standard 3
Complete & Accurate 3
Reusability 3
Total Marks 9
obtained