41.0k views
5 votes
Write a c program for diners philosopher problem. The condition is: in the output it should be specified that for eg P1 is eating and we input the status of P2 it should specify that P2 is thinking as no chopstick available

User Isuf
by
8.0k points

1 Answer

3 votes

Final answer:

The C program provided simulates the Diners Philosopher problem with two philosophers and two chopsticks, making use of threads and mutexes for synchronization. The program ensures that when one philosopher is eating, the other is thinking, as there are no available chopsticks.

Step-by-step explanation:

The Diners Philosopher problem in computer science is a classic synchronization problem when designing multi-threaded programs. This problem illustrates the challenges of avoiding deadlock, a situation where two or more processes are unable to proceed because each is waiting for the other to release a resource.

For simplicity, let's consider two philosophers (P1 and P2) and two chopsticks. When P1 is eating, it means P1 has acquired both chopsticks. Hence, if we check the status of P2 at that moment, P2 would be thinking since there are no chopsticks available for P2 to start eating.

Here is a simplified version of a C program that simulates this scenario using threads and mutexes:

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

#define NUM_PHILOSOPHERS 2

pthread_mutex_t chopsticks[NUM_PHILOSOPHERS];

void *philosopher(void *num) {
int phil = *(int *)num;

printf("P%d is thinking.\\", phil);
sleep(1);

pthread_mutex_lock(&chopsticks[phil]);
pthread_mutex_lock(&chopsticks[(phil + 1) % NUM_PHILOSOPHERS]);

printf("P%d is eating.\\", phil);
sleep(2);

pthread_mutex_unlock(&chopsticks[phil]);
pthread_mutex_unlock(&chopsticks[(phil + 1) % NUM_PHILOSOPHERS]);

printf("P%d is done eating and now thinking again.\\", phil);
return NULL;
}

int main() {
pthread_t philosophers[NUM_PHILOSOPHERS];
int phil_indices[NUM_PHILOSOPHERS] = {0, 1};

for (int i = 0; i < NUM_PHILOSOPHERS; ++i) {
pthread_mutex_init(&chopsticks[i], NULL);
}

for (int i = 0; i < NUM_PHILOSOPHERS; ++i) {
pthread_create(&philosophers[i], NULL, philosopher, &phil_indices[i]);
}

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

for (int i = 0; i < NUM_PHILOSOPHERS; ++i) {
pthread_mutex_destroy(&chopsticks[i]);
}

return 0;
}

When you run the program, it will output the status of each philosopher based on the availability of chopsticks. If a philosopher is eating, the next philosopher will not be able to eat (and will think) until the chopsticks are released.