Bankers Algorithm
Bankers Algorithm
h> }
int main() { if (flag == 0) {
int n, m, i, j, k; ans[ind++] = i;
printf("Enter the number of processes: "); for (y = 0; y < m; y++) {
scanf("%d", &n); avail[y] += alloc[i][y];
printf("Enter the number of resources: "); }
scanf("%d", &m); for(y=0;y<m;y++) {
int alloc[n][m]; if(t<=n)
int max[n][m]; ava[t][y]=avail[y];
printf("Enter the Allocation Matrix:\n"); }
for (i = 0; i < n; i++) { t++;
for (j = 0; j < m; j++) { printf ("\n");
scanf("%d", &alloc[i][j]); f[i] = 1;
} } }}}
} printf("\nProcess\tAllocation\tMax\t\tAvailable\tNeed\n");
printf("Enter the Maximum Matrix:\n"); for (i = 0; i < n; i++) {
for (i = 0; i < n; i++) { printf("P%d\t", i);
for (j = 0; j < m; j++) { for (j = 0; j < m; j++) {
scanf("%d", &max[i][j]); printf("%d ", alloc[i][j]);
} }
} printf("\t\t");
int avail[m]; for (j = 0; j < m; j++) {
printf("Enter the Available Resources:\n"); printf("%d ", max[i][j]);
for (i = 0; i < m; i++) { }
scanf("%d", &avail[i]); printf("\t\t");
} for(j=0;j<m;j++) {
int ava[n][m]; printf("%d ", ava[i][j]);
for(j=0;j<m;j++) { }
ava[0][j]=avail[j]; printf("\t\t");
} for(j=0;j<m;j++) {
// Printing Allocation, Need, and Maximum matrices printf("%d ", need[i][j]);
int f[n], ans[n], ind = 0; }
for (k = 0; k < n; k++) { printf("\n");
f[k] = 0; }
} int flag = 1;
int need[n][m]; for (i = 0; i < n; i++) {
for (i = 0; i < n; i++) { if (f[i] == 0) {
for (j = 0; j < m; j++) { flag = 0;
need[i][j] = max[i][j] - alloc[i][j]; printf("The following system is not safe");
} break;
} }
int t=1,y = 0; }
for (k = 0; k < n; k++) { if (flag == 1) {
for (i = 0; i < n; i++) { printf("Following is the SAFE Sequence\n");
if (f[i] == 0) { for (i = 0; i < n - 1; i++) {
int flag = 0; printf(" P%d ->", ans[i]);
for (j = 0; j < m; j++) { }
if (need[i][j] > avail[j]) { printf(" P%d", ans[n - 1]);
flag = 1;
break;
BANKERS ALGORITHM } return 0;
SEMOPHORES-Ex. 7 Mutual Exclusion and Synchronization using Semaphores in
Multi-threaded Programming"
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#define NUM_THREADS 5
pthread_exit(NULL);
int main() {
pthread_t threads[NUM_THREADS];
int thread_ids[NUM_THREADS];
thread_ids[i] = i + 1;
pthread_join(threads[i], NULL);
return 0; }
PROGRAM- DINING PHILOSOPHERS ALGORITHM
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<semaphore.h>
#include<unistd.h>
sem_t room;
sem_t chopstick[5];
sem_init(&room,0,4);
for(i=0;i<5;i++)
sem_init(&chopstick[i],0,1);
for(i=0;i<5;i++){
a[i]=i;
pthread_create(&tid[i],NULL,philosopher,(void *)&a[i]);
}
for(i=0;i<5;i++)
pthread_join(tid[i],NULL);
}
void * philosopher(void * num)
{
int phil=*(int *)num;
sem_wait(&room);
printf("Philosopher %d is thinking\n",phil);
sem_wait(&chopstick[phil]);
sem_wait(&chopstick[(phil+1)%5]);
eat(phil);
sleep(2);
printf("Philosopher %d has finished eating\n",phil);
sem_post(&chopstick[(phil+1)%5]);
sem_post(&chopstick[phil]);
sem_post(&room);
}