Exp.No.
: 06 Write a C program to implement Dining Philosopher Problem
Program:
#include <pthread.h> sem_post(&S[phnum]);
#include <semaphore.h> }
#include <stdio.h> }
#include <windows.h> // for Sleep function
#define N 5 // take up chopsticks
#define THINKING 2 void take_fork(int phnum) {
#define HUNGRY 1 sem_wait(&mutex);
#define EATING 0 // state that hungry
#define LEFT (phnum + 4) % N state[phnum] = HUNGRY;
#define RIGHT (phnum + 1) % N printf("Philosopher %d is Hungry\n", phnum + 1);
#define MAX_ITERATIONS 2// Define the maximum // eat if neighbours are not eating
number of iterations
test(phnum);
sem_post(&mutex);
int state[N];
// if unable to eat wait to be signalled
int phil[N] = { 0, 1, 2, 3, 4 };
sem_wait(&S[phnum]);
sem_t mutex;
Sleep(1000); // Sleep for 1 second
sem_t S[N];
}
void test(int phnum) {
// put down chopsticks
if (state[phnum] == HUNGRY && state[LEFT] !=
void put_fork(int phnum) {
EATING && state[RIGHT] != EATING) {
sem_wait(&mutex);
// state that eating
// state that thinking
state[phnum] = EATING;
state[phnum] = THINKING;
Sleep(2000); // Sleep for 2 seconds
printf("Philosopher %d putting fork %d and %d
printf("Philosopher %d takes fork %d and %d\n",
down\n", phnum + 1, LEFT + 1, phnum + 1);
phnum + 1, LEFT + 1, phnum + 1);
printf("Philosopher %d is thinking\n", phnum + 1);
printf("Philosopher %d is Eating\n", phnum + 1);
test(LEFT);
// sem_post(&S[phnum]) has no effect
test(RIGHT);
// during takefork
sem_post(&mutex);
// used to wake up hungry philosophers
}
// during putfork
void* philosopher(void* num) {
int* i = (int*)num; Output:
int iterations = 0; // Initialize the iteration counter
while (iterations < MAX_ITERATIONS) {
Sleep(1000); // Sleep for 1 second
take_fork(*i);
Sleep(0); // Sleep for 0 milliseconds
put_fork(*i);
iterations++; // Increment the iteration counter
return NULL;
int main() {
int i;
pthread_t thread_id[N];
// initialize the semaphores
sem_init(&mutex, 0, 1);
for (i = 0; i < 2; i++)
sem_init(&S[i], 0, 0);
for (i = 0; i < 5; i++) {
// create philosopher processes
pthread_create(&thread_id[i], NULL, philosopher,
(void*)&phil[i]);
printf("Philosopher %d is thinking\n", i + 1);
for (i = 0; i < 2; i++)
pthread_join(thread_id[i], NULL);
return 0;