VL2023240101008 Ast03
VL2023240101008 Ast03
Lab Assessment 3
Note:
Name: M.M.Sathvik
Reg no.: 21BCB0241
Lab course name: Operating Systems
Lab slot: L9+L10
1. Code the Banker’s algorithm in C and test the working of it with arbitrary inputs.
#include <stdio.h>
#include <stdbool.h>
if (canAllocate)
{
// Allocate resources for process i
for (k = 0; k < m; k++)
work[k] += allocation[i][k];
finish[i] = true;
found = true;
count++;
}
}
}
int main()
{
int i, j;
int n, m; // Number of processes and resources
return 0;
}
2. Write a C program to provide a solution for the classical synchronization problem
namely the Producer Consumer problem using POSIX Semaphores.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define BUFFER_SIZE 5
#define NUM_PRODUCERS 2
#define NUM_CONSUMERS 2
int buffer[BUFFER_SIZE];
int in = 0, out = 0;
sem_t emptySlots;
sem_t filledSlots;
pthread_mutex_t bufferLock;
while (1) {
// Produce an item
sleep(rand() % 3 + 1);
pthread_mutex_unlock(&bufferLock);
sem_post(&filledSlots);
item++;
}
pthread_exit(NULL);
}
pthread_mutex_unlock(&bufferLock);
sem_post(&emptySlots);
pthread_exit(NULL);
}
int main() {
// Initialize semaphores and mutex
sem_init(&emptySlots, 0, BUFFER_SIZE);
sem_init(&filledSlots, 0, 0);
pthread_mutex_init(&bufferLock, NULL);
return 0;
}
3. Write a C program to provide a solution to the Readers Writer problem using POSIX
Semaphores.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define NUM_READERS 5
#define NUM_WRITERS 2
int sharedData = 0;
int numReaders = 0;
sem_t rwMutex;
sem_t mutex;
while (1) {
// Acquire the mutex to update the number of readers
sem_wait(&mutex);
numReaders++;
if (numReaders == 1) {
// First reader, acquire the rwMutex to prevent writers
sem_wait(&rwMutex);
}
sem_post(&mutex);
pthread_exit(NULL);
}
while (1) {
// Acquire the rwMutex to write
sem_wait(&rwMutex);
pthread_exit(NULL);
}
int main() {
// Initialize semaphores
sem_init(&rwMutex, 0, 1);
sem_init(&mutex, 0, 1);
// Destroy semaphores
sem_destroy(&rwMutex);
sem_destroy(&mutex);
return 0;
}