Practical No. 5 OS - Dinning Philosopher Problem Using Semaphores
Practical No. 5 OS - Dinning Philosopher Problem Using Semaphores
41
Name Atharva Sharma
Semester IV
Section A
Batch A2
Practical No. 5
Theory The Dining Philosopher Problem – The Dining Philosopher Problem states that K
philosophers seated around a circular table with one chopstick between each pair of
philosophers. There is one chopstick between each philosopher. A philosopher may
eat if he can pick up the two chopsticks adjacent to him. One chopstick may be
picked up by any one of its adjacent followers but not both.
There are three states of the philosopher: THINKING, HUNGRY, and EATING. Here
there are two semaphores: Mutex and a semaphore array for the philosophers.
Mutex is used such that no two philosophers may access the pickup or putdown at
the same time. The array is used to control the behavior of each philosopher. But,
semaphores can result in deadlock due to programming errors.
Program #include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#define N 5
#define THINKING 2
#define HUNGRY 1
#define EATING 0
#define LEFT (phnum + 4) % N
#define RIGHT (phnum + 1) % N
int state[N];
int phil[N] = { 0, 1, 2, 3, 4 };
sem_t mutex;
sem_t S[N];
// take up chopsticks
void take_fork(int phnum)
{
sem_wait(&mutex);
sem_post(&mutex);
sleep(1);
}
sem_wait(&mutex);
sem_post(&mutex);
}
while (1) {
int* i = num;
sleep(1);
take_fork(*i);
sleep(0);
put_fork(*i);
}
}
int main()
{
int i;
pthread_t thread_id[N];
sem_init(&S[i], 0, 0);
pthread_join(thread_id[i], NULL);
}
Output