Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

write a programm the question says Exercise 39-Chapter 6 A student majoring in a

ID: 3919429 • Letter: W

Question

write a programm the question says

Exercise 39-Chapter 6

A student majoring in anthropology and minoring in computer science has embarked on a research project to see if African baboons can be taught about deadlocks. He locates a deep canyon and fastens a rope across it, so the baboons can cross hand-overhand. Several baboons can cross at the same time, provided that they are all going in the same direction. If eastward-moving and westward-moving baboons ever get onto the rope at the same time, a deadlock will result (the baboons will get stuck in the middle) because it is impossible for one baboon to climb over another one while suspended over the canyon. If a baboon wants to cross the canyon, he must check to see that no other baboon is currently crossing in the opposite direction. Write a program using semaphores that avoids deadlock. Do not worry about a series of eastward-moving baboons holding up the westward-moving baboons indefinitely.

Explanation / Answer

Please find the followinv code

========================

enum direction { WEST=0, EAST=1 };
Semaphore mutex; // initially 1, protect critical sections
Semaphore blocked[2];
// one for each direction. Each initially 0, so always sleep on first P
int blockedCnt[2]; // number of baboons waiting on each side
int travellers[2]; // number of baboons on the rope heading each direction
//(at least one is zero at any time)
Baboon(direction dir) {
int revdir = !dir; // the reverse direction
mutex->P();
while (travellers[revdir]) {
blockedCnt[dir]++; // announce our intention to block
mutex->V(); // trade mutex for block
blocked[dir]->P();
mutex->P();
}
travellers[dir]++; // we’re free to cross
mutex->V();
// cross bridge.
mutex->P();
travellers[dir]--;
if (!travellers[dir]) {
// if we’re the last one heading this way,
// wakeup baboons waiting for us to finish.
while(blockedCnt[revdir]--)
blocked[revdir]->V();
}
mutex->V();
}

===============================

Hope this will help

Please comment for any clarifications