Professional Documents
Culture Documents
Problems
Name Reg No
Objective:
Producer/Consumer Problem
Producer/Consumer Problem
Code
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <semaphore.h>
int main() {
const char *memName = "shmem";
int shm_fd = shm_open(memName, O_CREAT | O_RDWR, 0666);
ftruncate(shm_fd, sizeof(int));
int *buffer = mmap(0, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED
if (pid == 0) {
for (int i = 0; i < 5; ++i) {
// Wait until there is atleast one Item prod
sem_wait(full);
printf("Consumer consumed: %d\n", *buffer);
// Indicate one item Consumed
sem_post(empty);
}
exit(EXIT_SUCCESS);
} else {
for (int i = 0; i < 5; ++i) {
// Wait until there is atleast one empty slot
sem_wait(empty);
*buffer = i;
printf("Producer produced: %d\n", i);
// Indicate one slot is now filled
sem_post(full);
}
return 0;
}
OUTPUT
Buffer size as 1
Here we can clearly see as the buffer size is only 1, the producer produces 1, and
then have to wait until that 1 item is consumed before producing more items.
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <unistd.h>
sem_t forks[5];
int main() {
pthread_t philosophers[5];
int philosopher_numbers[5];
return 0;
}
while (1) {
printf("Philosopher %d is thinking.\n", philosopher_number);
sem_wait(&forks[philosopher_number]);
printf("Philosopher %d picked up left fork.\n", philosopher_number
sem_wait(&forks[(philosopher_number + 1) % 5]);
printf("Philosopher %d picked up right fork - now eating.\n", phil
sleep(1);
sem_post(&forks[(philosopher_number + 1) % 5]);
sem_post(&forks[philosopher_number]);
OUTPUT