Experiment 9
Experiment 9
Sample 1
Aim
Algorithm
The basic idea is to prevent deadlock and ensure that no philosopher is starving (waiting
indefinitely). The solution uses semaphores to ensure mutual exclusion while picking up
chopsticks.
Pseudo Code
Here's the pseudo code for the Dining Philosophers problem using semaphores:
1. Initialize Semaphores:
○ Initialize one semaphore for each chopstick.
○ Initialize a semaphore to limit the number of philosophers that can sit at the
table simultaneously to N-1.
2. Philosopher's Routine:
○ Wait for the semaphore that limits the number of philosophers.
○ Wait for the semaphore for the left chopstick.
○ Wait for the semaphore for the right chopstick.
○ Eat.
○ Signal the semaphore for the right chopstick.
○ Signal the semaphore for the left chopstick.
○ Signal the semaphore that limits the number of philosophers.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#define NUM_PHILOSOPHERS 5
#define NUM_CHOPSTICKS 5
int main() {
int i, a[NUM_PHILOSOPHERS];
pthread_t tid[NUM_PHILOSOPHERS]; // threads for philosophers
return 0;
}
// Eat
eat(phil);
sleep(2);
printf("\nPhilosopher %d has finished eating", phil);
// Leave room
sem_post(&room);
return NULL;
}
Output-
Sample -2
Aim
The aim of the second sample program is to implement the Dining Philosophers problem
using mutexes to synchronize access to shared resources (chopsticks). This implementation
ensures that no two philosophers can pick up the same chopstick simultaneously, preventing
deadlock and starvation.
Pseudo Code
Here is the pseudo code for the Dining Philosophers problem using mutexes:
1. Initialize Mutexes:
○ Initialize one mutex for each chopstick.
2. Philosopher's Routine:
○ Think.
○ Lock the left chopstick's mutex.
○ Lock the right chopstick's mutex.
○ Eat.
○ Unlock the right chopstick's mutex.
○ Unlock the left chopstick's mutex.
○ Finish eating and go back to thinking.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#define NUM_PHILOSOPHERS 5
#define NUM_CHOPSTICKS 5
pthread_t philosopher[NUM_PHILOSOPHERS];
pthread_mutex_t chopstick[NUM_CHOPSTICKS];
int main() {
int i, status_message;
void* msg;
// Pick up chopsticks
if (n == NUM_PHILOSOPHERS - 1) {
pthread_mutex_lock(&chopstick[(n + 1) % NUM_CHOPSTICKS]);
pthread_mutex_lock(&chopstick[n]);
} else {
pthread_mutex_lock(&chopstick[n]);
pthread_mutex_lock(&chopstick[(n + 1) % NUM_CHOPSTICKS]);
}
// Eat
printf("\nPhilosopher %d is eating", n);
sleep(3);
Output -