0% found this document useful (0 votes)
22 views

Abhi 4a

Uploaded by

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

Abhi 4a

Uploaded by

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

Assignment no 4(a)

// Abhiraje Nimbalkar
//Roll No: 33
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>

#define BUFFER_SIZE 5 // Size of the buffer


#define NUM_ITEMS 20 // Total number of items to produce/consume

int buffer[BUFFER_SIZE];
int in = 0; // Index for the next produced item
int out = 0; // Index for the next consumed item

sem_t empty; // Semaphore to count empty slots in the buffer


sem_t full; // Semaphore to count full slots in the buffer
pthread_mutex_t mutex; // Mutex for synchronizing access to the buffer

void* producer(void* arg) {


for (int i = 0; i < NUM_ITEMS; i++) {
// Produce an item
int item = rand() % 100; // Random item
sleep(rand() % 2); // Simulate production time

// Wait for an empty slot


sem_wait(&empty);

// Lock the buffer


pthread_mutex_lock(&mutex);

// Add the item to the buffer


buffer[in] = item;
printf("Producer produced: %d\n", item);
in = (in + 1) % BUFFER_SIZE; // Move to the next index

// Unlock the buffer


pthread_mutex_unlock(&mutex);

// Signal that a new item is available


sem_post(&full);
}
return NULL;
}

void* consumer(void* arg) {


for (int i = 0; i < NUM_ITEMS; i++) {
// Wait for an available item
sem_wait(&full);

// Lock the buffer


pthread_mutex_lock(&mutex);

// Remove the item from the buffer


int item = buffer[out];
printf("Consumer consumed: %d\n", item);
out = (out + 1) % BUFFER_SIZE; // Move to the next index

// Unlock the buffer


pthread_mutex_unlock(&mutex);

// Signal that an empty slot is available


sem_post(&empty);

sleep(rand() % 2); // Simulate consumption time


}
return NULL;
}

int main() {
pthread_t prod_thread, cons_thread;

// Initialize semaphores and mutex


sem_init(&empty, 0, BUFFER_SIZE); // Initially, all slots are empty
sem_init(&full, 0, 0); // Initially, no items are full
pthread_mutex_init(&mutex, NULL);

// Create producer and consumer threads


pthread_create(&prod_thread, NULL, producer, NULL);
pthread_create(&cons_thread, NULL, consumer, NULL);

// Wait for the threads to finish


pthread_join(prod_thread, NULL);
pthread_join(cons_thread, NULL);

// Clean up
sem_destroy(&empty);
sem_destroy(&full);
pthread_mutex_destroy(&mutex);

return 0;
}

You might also like