OS Lab Assignment 6 Bakery Simulation Suhani Bansal With Output
OS Lab Assignment 6 Bakery Simulation Suhani Bansal With Output
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
int buffer[SIZE];
int in = 0, out = 0;
void* producer(void* p) {
int item;
for (int i = 0; i < 10; i++) {
item = rand() % 100;
sem_wait(&empty);
pthread_mutex_lock(&mutex);
buffer[in] = item;
printf("Baker produced bread %d at slot %d\n", item, in);
in = (in + 1) % SIZE;
pthread_mutex_unlock(&mutex);
sem_post(&full);
sleep(1);
}
return NULL;
}
void* consumer(void* c) {
int item;
for (int i = 0; i < 10; i++) {
sem_wait(&full);
pthread_mutex_lock(&mutex);
item = buffer[out];
printf("Customer bought bread %d from slot %d\n", item, out);
out = (out + 1) % SIZE;
pthread_mutex_unlock(&mutex);
sem_post(&empty);
sleep(2);
}
return NULL;
}
int main() {
pthread_t prod, cons;
sem_init(&empty, 0, SIZE);
sem_init(&full, 0, 0);
pthread_mutex_init(&mutex, NULL);
pthread_join(prod, NULL);
pthread_join(cons, NULL);
sem_destroy(&empty);
sem_destroy(&full);
pthread_mutex_destroy(&mutex);
return 0;
}
Sample Output