Dining Philosopher Sleeping Barber Id32
Dining Philosopher Sleeping Barber Id32
Assignment
Submitted to,
Submitted by,
Pseudo-Code: }
}
#define N 5
typedef int semaphore;
#define LEFT (i + N - 1) % N
#define RIGHT (i + 1) % N void take_forks(int i) {
down(&mutex);
#define THINKING 0 state[i] = HUNGRY;
#define HUNGRY 1 test(i);
#define EATING 2 up(&mutex);
down(&s[i]);
int state[N]; }
semaphore mutex = 1;
semaphore s[N]; void put_forks(int i) {
down(&mutex);
void philosopher(int i) { state[i] = THINKING;
while (TRUE) { test(LEFT);
think(); test(RIGHT);
take_forks(i); up(&mutex);
eat(); }
put_forks(i);
void test(int i) { state[i] = EATING;
if (state[i] == HUNGRY && up(&s[i]);
state[LEFT] != EATING && }
state[RIGHT] != EATING) { }
Explanation:
- Each philosopher follows a routine of thinking, attempting to acquire
forks, eating, and putting down forks.
- The state array keeps track of the philosopher's status (`THINKING`,
`HUNGRY`, or `EATING`).
- The `mutex` semaphore ensures exclusive access to modify the
philosopher's state.
- The `test` function checks adjacent philosophers' states to permit a
philosopher to start eating without causing deadlock.
This solution shows that all philosophers eventually get a chance to eat,
avoiding deadlock by releasing forks if they can't be acquired.
Description:
The Sleeping Barber Problem shows a scenario with one barber, a barber
chair, and a number of chairs for waiting customer. The challenge is to
synchronize the barber's activity with customer arrivals, ensuring the
barber serves customer when available and rest when there is no one.
Customers must be served by the barber or leave if there are no chairs.
Pseudo-Code:
#define CHAIRS 5
typedef int semaphore;
semaphore customers = 0;
semaphore barbers = 0;
semaphore mutex = 1;
int waiting = 0;
void barber(void) {
while (TRUE) {
down(&customers); // Sleep if no customers are waiting
down(&mutex); // Acquire access to 'waiting'
waiting = waiting - 1; // Decrement count of waiting customers
up(&barbers); // Barber is now ready to cut hair
up(&mutex); // Release 'waiting'
cut_hair(); // Barber cuts hair (outside critical region)
}
}
void customer(void) {
down(&mutex); // Enter critical region
if (waiting < CHAIRS) { // If no free chairs, leave
waiting = waiting + 1; // Increment count of waiting customers
up(&customers); // Wake up barber if necessary
up(&mutex); // Release access to 'waiting'
down(&barbers); // Sleep if no free barbers
get_haircut(); // Be seated and served
} else {
up(&mutex); // Shop is full; do not wait
}
}
Explanation:
- The solution uses semaphores (customer, barbers, mutex) to synchronize
the actions of the barber and customers.
- Customers arrive, check for available seating, and signal the barber if they
can be served.
- The barber waits for customers to arrive and serves them one by one,
ensuring mutual exclusion and proper synchronization that avoids race
condition.