0% found this document useful (0 votes)
30 views8 pages

VL2023240101008 Ast03

The document contains 3 questions asking to write C programs that demonstrate operating systems concepts: 1. Code the Banker's algorithm to check if a system is in a safe state using arbitrary inputs. 2. Write a program to solve the producer-consumer problem using POSIX semaphores for synchronization between producer and consumer threads. 3. Write a program to solve the readers-writers problem using POSIX semaphores to allow multiple readers or a single writer access to shared data.

Uploaded by

Sathvik Muppidi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views8 pages

VL2023240101008 Ast03

The document contains 3 questions asking to write C programs that demonstrate operating systems concepts: 1. Code the Banker's algorithm to check if a system is in a safe state using arbitrary inputs. 2. Write a program to solve the producer-consumer problem using POSIX semaphores for synchronization between producer and consumer threads. 3. Write a program to solve the readers-writers problem using POSIX semaphores to allow multiple readers or a single writer access to shared data.

Uploaded by

Sathvik Muppidi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Operating Systems

Lab Assessment 3

Note:

Upload file must contain the following:


Name, Register number, Lab course name, Lab slot, Lab Assessment title
The following for every question o
Question text o Source code
o Snapshot of execution sequence with atleast two sample inputs (wherever
applicable). Terminal /Shell prompt/workingenvironment should carry your
name/register number

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>

// Maximum number of processes


#define MAX_PROCESSES 10

// Maximum number of resources


#define MAX_RESOURCES 10

// Function to check if a process can be allocated resources


bool isSafe(int processes[], int available[], int max[][MAX_RESOURCES], int
allocation[][MAX_RESOURCES], int n, int m)
{
    int i, j, k;
    int work[m];
    bool finish[n];

    // Initialize the work and finish arrays


    for (i = 0; i < m; i++)
        work[i] = available[i];

    for (i = 0; i < n; i++)


        finish[i] = false;

    // Find an unallocated process that can be executed


    int count = 0;
    while (count < n)
    {
        bool found = false;
        for (i = 0; i < n; i++)
        {
            if (finish[i] == false)
            {
                // Check if all resources for process i can be allocated
                bool canAllocate = true;
                for (j = 0; j < m; j++)
                {
                    if (max[i][j] - allocation[i][j] > work[j])
                    {
                        canAllocate = false;
                        break;
                    }
                }

                if (canAllocate)
                {
                    // Allocate resources for process i
                    for (k = 0; k < m; k++)
                        work[k] += allocation[i][k];

                    finish[i] = true;
                    found = true;
                    count++;
                }
            }
        }

        // If no process can be allocated, the system is in an unsafe state


        if (found == false)
            return false;
    }

    // If all processes have been allocated, the system is in a safe state


    return true;
}

int main()
{
    int i, j;
    int n, m; // Number of processes and resources

    printf("Enter the number of processes: ");


    scanf("%d", &n);
    printf("Enter the number of resources: ");
    scanf("%d", &m);

    int processes[MAX_PROCESSES]; // Array to store process IDs


    int available[MAX_RESOURCES]; // Array to store the number of available
resources

    printf("Enter the process IDs:\n");


    for (i = 0; i < n; i++)
        scanf("%d", &processes[i]);

    printf("Enter the number of available resources:\n");


    for (i = 0; i < m; i++)
        scanf("%d", &available[i]);

    int max[MAX_PROCESSES][MAX_RESOURCES];       // Maximum resource matrix


    int allocation[MAX_PROCESSES][MAX_RESOURCES]; // Allocation matrix

    printf("Enter the maximum resource matrix:\n");


    for (i = 0; i < n; i++)
    {
        for (j = 0; j < m; j++)
            scanf("%d", &max[i][j]);
    }

    printf("Enter the allocation matrix:\n");


    for (i = 0; i < n; i++)
    {
        for (j = 0; j < m; j++)
            scanf("%d", &allocation[i][j]);
    }

    // Check if the system is in a safe state


    if (isSafe(processes, available, max, allocation, n, m))
        printf("The system is in a safe state.\n");
    else
        printf("The system is in an unsafe state.\n");

    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;

void *producer(void *arg) {


    int producerId = *((int *)arg);
    int item = 1;

    while (1) {
        // Produce an item
        sleep(rand() % 3 + 1);

        // Wait for an empty slot in the buffer


        sem_wait(&emptySlots);
        pthread_mutex_lock(&bufferLock);

        // Add the item to the buffer


        buffer[in] = item;
        printf("Producer %d produced item %d\n", producerId, item);
        in = (in + 1) % BUFFER_SIZE;

        pthread_mutex_unlock(&bufferLock);
        sem_post(&filledSlots);

        item++;
    }

    pthread_exit(NULL);
}

void *consumer(void *arg) {


    int consumerId = *((int *)arg);
    while (1) {
        // Wait for a filled slot in the buffer
        sem_wait(&filledSlots);
        pthread_mutex_lock(&bufferLock);

        // Consume an item from the buffer


        int item = buffer[out];
        printf("Consumer %d consumed item %d\n", consumerId, item);
        out = (out + 1) % BUFFER_SIZE;

        pthread_mutex_unlock(&bufferLock);
        sem_post(&emptySlots);

        // Consume the item


        sleep(rand() % 3 + 1);
    }

    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);

    // Create producer threads


    pthread_t producerThreads[NUM_PRODUCERS];
    int producerIds[NUM_PRODUCERS];
    for (int i = 0; i < NUM_PRODUCERS; i++) {
        producerIds[i] = i + 1;
        pthread_create(&producerThreads[i], NULL, producer, (void
*)&producerIds[i]);
    }

    // Create consumer threads


    pthread_t consumerThreads[NUM_CONSUMERS];
    int consumerIds[NUM_CONSUMERS];
    for (int i = 0; i < NUM_CONSUMERS; i++) {
        consumerIds[i] = i + 1;
        pthread_create(&consumerThreads[i], NULL, consumer, (void
*)&consumerIds[i]);
    }

    // Join producer threads


    for (int i = 0; i < NUM_PRODUCERS; i++) {
        pthread_join(producerThreads[i], NULL);
    }
    // Join consumer threads
    for (int i = 0; i < NUM_CONSUMERS; i++) {
        pthread_join(consumerThreads[i], NULL);
    }

    // Destroy semaphores and mutex


    sem_destroy(&emptySlots);
    sem_destroy(&filledSlots);
    pthread_mutex_destroy(&bufferLock);

    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;

void *reader(void *arg) {


    int readerId = *((int *)arg);

    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);

        // Read shared data


        printf("Reader %d read shared data: %d\n", readerId, sharedData);

        // Release the mutex after reading


        sem_wait(&mutex);
        numReaders--;
        if (numReaders == 0) {
            // Last reader, release the rwMutex to allow writers
            sem_post(&rwMutex);
        }
        sem_post(&mutex);

        // Perform additional processing


        sleep(rand() % 3 + 1);
    }

    pthread_exit(NULL);
}

void *writer(void *arg) {


    int writerId = *((int *)arg);

    while (1) {
        // Acquire the rwMutex to write
        sem_wait(&rwMutex);

        // Write to shared data


        sharedData++;
        printf("Writer %d wrote to shared data: %d\n", writerId, sharedData);

        // Release the rwMutex after writing


        sem_post(&rwMutex);

        // Perform additional processing


        sleep(rand() % 3 + 1);
    }

    pthread_exit(NULL);
}

int main() {
    // Initialize semaphores
    sem_init(&rwMutex, 0, 1);
    sem_init(&mutex, 0, 1);

    // Create reader threads


    pthread_t readerThreads[NUM_READERS];
    int readerIds[NUM_READERS];
    for (int i = 0; i < NUM_READERS; i++) {
        readerIds[i] = i + 1;
        pthread_create(&readerThreads[i], NULL, reader, (void
*)&readerIds[i]);
    }

    // Create writer threads


    pthread_t writerThreads[NUM_WRITERS];
    int writerIds[NUM_WRITERS];
    for (int i = 0; i < NUM_WRITERS; i++) {
        writerIds[i] = i + 1;
        pthread_create(&writerThreads[i], NULL, writer, (void
*)&writerIds[i]);
    }

    // Join reader threads


    for (int i = 0; i < NUM_READERS; i++) {
        pthread_join(readerThreads[i], NULL);
    }

    // Join writer threads


    for (int i = 0; i < NUM_WRITERS; i++) {
        pthread_join(writerThreads[i], NULL);
    }

    // Destroy semaphores
    sem_destroy(&rwMutex);
    sem_destroy(&mutex);

    return 0;
}

You might also like