#include <gtk/gtk.h>
#include <stdio.h>
#define P 5 // Number of processes
#define R 3 // Number of resources
int available[R] = {3, 3, 2}; // Example available resources
int max[P][R] = {{7, 5, 3}, {3, 2, 2}, {9, 0, 2}, {2, 2, 2}, {4, 3, 3}};
int allocation[P][R] = {{0, 1, 0}, {2, 0, 0}, {3, 0, 2}, {2, 1, 1}, {0, 0, 2}};
int need[P][R];
GtkWidget *output_label;
// Function to calculate need matrix
void calculate_need() {
for (int i = 0; i < P; i++)
for (int j = 0; j < R; j++)
need[i][j] = max[i][j] - allocation[i][j];
}
// Banker's algorithm implementation
void bankers_algorithm() {
calculate_need();
int finish[P] = {0}, safe_sequence[P], work[R];
for (int i = 0; i < R; i++)
work[i] = available[i];
int count = 0;
while (count < P) {
int found = 0;
for (int p = 0; p < P; p++) {
if (finish[p] == 0) {
int j;
for (j = 0; j < R; j++)
if (need[p][j] > work[j])
break;
if (j == R) {
for (int k = 0; k < R; k++)
work[k] += allocation[p][k];
safe_sequence[count++] = p;
finish[p] = 1;
found = 1;
}
}
}
if (found == 0) {
gtk_label_set_text(GTK_LABEL(output_label), "No safe sequence found.");
return;
}
}
char result[256];
sprintf(result, "Safe sequence is: ");
for (int i = 0; i < P; i++) {
char temp[5];
sprintf(temp, "P%d ", safe_sequence[i]);
strcat(result, temp);
}
gtk_label_set_text(GTK_LABEL(output_label), result);
}
// Callback for button click
void on_button_clicked(GtkWidget *widget, gpointer data) {
bankers_algorithm();
}
int main(int argc, char *argv[]) {
GtkWidget *window;
GtkWidget *button;
GtkWidget *vbox;
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window), "Banker's Algorithm");
gtk_container_set_border_width(GTK_CONTAINER(window), 10);
gtk_window_set_default_size(GTK_WINDOW(window), 300, 200);
vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 5);
gtk_container_add(GTK_CONTAINER(window), vbox);
button = gtk_button_new_with_label("Run Banker's Algorithm");
g_signal_connect(button, "clicked", G_CALLBACK(on_button_clicked), NULL);
gtk_box_pack_start(GTK_BOX(vbox), button, TRUE, TRUE, 0);
output_label = gtk_label_new("Output will be shown here...");
gtk_box_pack_start(GTK_BOX(vbox), output_label, TRUE, TRUE, 0);
g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
gtk_widget_show_all(window);
gtk_main();
return 0;
}