You are on page 1of 5

Week 8 - Process Synchronization

Problems

Name Reg No

Yash Rathi 22BCE1892

Objective:

Implement the following problems:

Producer/Consumer Problem

Dining Philosopher 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

sem_t *empty = sem_open("empty", O_CREAT, 0644, 1);


sem_t *full = sem_open("full", O_CREAT, 0644, 0);

pid_t pid = fork();


if (pid < 0) {
perror("fork failed");
exit(EXIT_FAILURE);
}

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.

Thinking Philoshophers Problem

Code using threads

#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <unistd.h>

sem_t forks[5];

void* philosopher(void* num);

int main() {
pthread_t philosophers[5];
int philosopher_numbers[5];

for (int i = 0; i < 5; i++) {


sem_init(&forks[i], 0, 1);
}

for (int i = 0; i < 5; i++) {


philosopher_numbers[i] = i;
pthread_create(&philosophers[i], NULL, philosopher, &philosopher_n
}

for (int i = 0; i < 5; i++) {


pthread_join(philosophers[i], NULL);
}

for (int i = 0; i < 5; i++) {


sem_destroy(&forks[i]);
}

return 0;
}

void* philosopher(void* num) {


int philosopher_number = *(int*)num;

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

printf("Philosopher %d put down both forks - now thinking.\n", phi


}
}

OUTPUT

You might also like