7.
Write a C program to implement Producer-
Consumer Problem.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#define BUFFER_SIZE 5
int buffer[BUFFER_SIZE];
int in = 0, out = 0;
sem_t empty, full;
pthread_mutex_t mutex;
void* producer(void* arg) {
for (int i = 0; i < 10; i++) {
int item = rand() % 100;
sem_wait(&empty);
pthread_mutex_lock(&mutex);
buffer[in] = item;
printf("Producer produced: %d at index %d\n", item, in);
in = (in + 1) % BUFFER_SIZE;
pthread_mutex_unlock(&mutex);
sem_post(&full);
sleep(1);
}
return NULL;
}
void* consumer(void* arg) {
for (int i = 0; i < 10; i++) {
sem_wait(&full);
pthread_mutex_lock(&mutex);
int item = buffer[out];
printf("Consumer consumed: %d from index %d\n", item, out);
out = (out + 1) % BUFFER_SIZE;
pthread_mutex_unlock(&mutex);
sem_post(&empty);
sleep(2);
}
return NULL;
}
int main() {
pthread_t prod, cons;
pthread_mutex_init(&mutex, NULL);
sem_init(&empty, 0, BUFFER_SIZE);
sem_init(&full, 0, 0);
pthread_create(&prod, NULL, producer, NULL);
pthread_create(&cons, NULL, consumer, NULL);
pthread_join(prod, NULL);
pthread_join(cons, NULL);
pthread_mutex_destroy(&mutex);
sem_destroy(&empty);
sem_destroy(&full);
return 0;
}
Output
8.) Write a C program to implement
Banker’s Algorithm.
#include <stdio.h>
#include <stdbool.h>
#define MAX_PROCESSES 10
#define MAX_RESOURCES 10
int main() {
int n, m;
int allocation[MAX_PROCESSES][MAX_RESOURCES];
int max[MAX_PROCESSES][MAX_RESOURCES];
int need[MAX_PROCESSES][MAX_RESOURCES];
int available[MAX_RESOURCES];
int finish[MAX_PROCESSES] = {0};
int safeSequence[MAX_PROCESSES];
printf("Enter number of processes: ");
scanf("%d", &n);
printf("Enter number of resources: ");
scanf("%d", &m);
printf("Enter Allocation Matrix:\n");
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
scanf("%d", &allocation[i][j]);
printf("Enter Maximum Matrix:\n");
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
scanf("%d", &max[i][j]);
printf("Enter Available Resources:\n");
for (int i = 0; i < m; i++)
scanf("%d", &available[i]);
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
need[i][j] = max[i][j] - allocation[i][j];
int count = 0;
while (count < n) {
bool found = false;
for (int i = 0; i < n; i++) {
if (!finish[i]) {
bool canExecute = true;
for (int j = 0; j < m; j++) {
if (need[i][j] > available[j]) {
canExecute = false;
break;
}
}
if (canExecute) {
for (int k = 0; k < m; k++)
available[k] += allocation[i][k];
safeSequence[count++] = i;
finish[i] = 1;
found = true;
}
}
}
if (!found) {
printf("System is not in a safe state.\n");
return 1;
}
}
printf("System is in a safe state.\nSafe sequence is: ");
for (int i = 0; i < n; i++)
printf("P%d ", safeSequence[i]);
printf("\n");
return 0;
}
Output