Question

In: Computer Science

(Full Program)Write code that shows how deadlocks work. Then write code that shows a fix using...

  1. (Full Program)Write code that shows how deadlocks work. Then write code that shows a fix using semaphores.

  1. (Full program)Write code showing the elevator algorithm.

c++ Language

Solutions

Expert Solution

a) Dining philosophers problem using semaphore in c++:

#include<iostream>

#define n 4

using namespace std;

int compltedPhilo = 0,i;

struct fork{
   int taken;
}ForkAvil[n];

struct philosp{
   int left;
   int right;
}Philostatus[n];

void goForDinner(int philID){ //same like threads concept here cases implemented
   if(Philostatus[philID].left==10 && Philostatus[philID].right==10)
cout<<"Philosopher "<<philID+1<<" completed his dinner\n";
   //if already completed dinner
   else if(Philostatus[philID].left==1 && Philostatus[philID].right==1){
//if just taken two forks
cout<<"Philosopher "<<philID+1<<" completed his dinner\n";

Philostatus[philID].left = Philostatus[philID].right = 10; //remembering that he completed dinner by assigning value 10
int otherFork = philID-1;

if(otherFork== -1)
otherFork=(n-1);

ForkAvil[philID].taken = ForkAvil[otherFork].taken = 0; //releasing forks
cout<<"Philosopher "<<philID+1<<" released fork "<<philID+1<<" and fork "<<otherFork+1<<"\n";
compltedPhilo++;
}
else if(Philostatus[philID].left==1 && Philostatus[philID].right==0){ //left already taken, trying for right fork
if(philID==(n-1)){
if(ForkAvil[philID].taken==0){ //KEY POINT OF THIS PROBLEM, THAT LAST PHILOSOPHER TRYING IN reverse DIRECTION
ForkAvil[philID].taken = Philostatus[philID].right = 1;
cout<<"Fork "<<philID+1<<" taken by philosopher "<<philID+1<<"\n";
}else{
cout<<"Philosopher "<<philID+1<<" is waiting for fork "<<philID+1<<"\n";
}
}else{ //except last philosopher case
int dupphilID = philID;
philID-=1;

if(philID== -1)
philID=(n-1);

if(ForkAvil[philID].taken == 0){
ForkAvil[philID].taken = Philostatus[dupphilID].right = 1;
cout<<"Fork "<<philID+1<<" taken by Philosopher "<<dupphilID+1<<"\n";
}else{
cout<<"Philosopher "<<dupphilID+1<<" is waiting for Fork "<<philID+1<<"\n";
}
}
}
else if(Philostatus[philID].left==0){ //nothing taken yet
if(philID==(n-1)){
if(ForkAvil[philID-1].taken==0){ //KEY POINT OF THIS PROBLEM, THAT LAST PHILOSOPHER TRYING IN reverse DIRECTION
ForkAvil[philID-1].taken = Philostatus[philID].left = 1;
cout<<"Fork "<<philID<<" taken by philosopher "<<philID+1<<"\n";
}else{
cout<<"Philosopher "<<philID+1<<" is waiting for fork "<<philID<<"\n";
}
}else{ //except last philosopher case
if(ForkAvil[philID].taken == 0){
ForkAvil[philID].taken = Philostatus[philID].left = 1;
cout<<"Fork "<<philID+1<<" taken by Philosopher "<<philID+1<<"\n";
}else{
cout<<"Philosopher "<<philID+1<<" is waiting for Fork "<<philID+1<<"\n";
}
}
}else{}
}

int main(){
   for(i=0;i<n;i++)
ForkAvil[i].taken=Philostatus[i].left=Philostatus[i].right=0;

   while(compltedPhilo<n){
       /* Observe here carefully, while loop will run until all philosophers complete dinner
       Actually problem of deadlock occur only thy try to take at same time
       This for loop will say that they are trying at same time. And remaining status will print by go for dinner function
       */
       for(i=0;i<n;i++)
goForDinner(i);
       cout<<"\nTill now num of philosophers completed dinner are "<<compltedPhilo<<"\n\n";
   }

   return 0;
}

*********************************************************************************************************************************************

b) Elevator algorithm in c++:

// C++ program to demonstrate

// SCAN Disk Scheduling algorithm

  

#include <bits/stdc++.h>

using namespace std;

  

int size = 8;

int disk_size = 200;

  

void SCAN(int arr[], int head, string direction)

{

    int seek_count = 0;

    int distance, cur_track;

    vector<int> left, right;

    vector<int> seek_sequence;

  

    // appending end values

    // which has to be visited

    // before reversing the direction

    if (direction == "left")

        left.push_back(0);

    else if (direction == "right")

        right.push_back(disk_size - 1);

  

    for (int i = 0; i < size; i++) {

        if (arr[i] < head)

            left.push_back(arr[i]);

        if (arr[i] > head)

            right.push_back(arr[i]);

    }

  

    // sorting left and right vectors

    std::sort(left.begin(), left.end());

    std::sort(right.begin(), right.end());

  

    // run the while loop two times.

    // one by one scanning right

    // and left of the head

    int run = 2;

    while (run--) {

        if (direction == "left") {

            for (int i = left.size() - 1; i >= 0; i--) {

                cur_track = left[i];

  

                // appending current track to seek sequence

                seek_sequence.push_back(cur_track);

  

                // calculate absolute distance

                distance = abs(cur_track - head);

  

                // increase the total count

                seek_count += distance;

  

                // accessed track is now the new head

                head = cur_track;

            }

            direction = "right";

        }

        else if (direction == "right") {

            for (int i = 0; i < right.size(); i++) {

                cur_track = right[i];

                // appending current track to seek sequence

                seek_sequence.push_back(cur_track);

  

                // calculate absolute distance

                distance = abs(cur_track - head);

  

                // increase the total count

                seek_count += distance;

  

                // accessed track is now new head

                head = cur_track;

            }

            direction = "left";

        }

    }

  

    cout << "Total number of seek operations = "

         << seek_count << endl;

  

    cout << "Seek Sequence is" << endl;

  

    for (int i = 0; i < seek_sequence.size(); i++) {

        cout << seek_sequence[i] << endl;

    }

}

  

// Driver code

int main()

{

  

    // request array

    int arr[size] = { 176, 79, 34, 60,

                      92, 11, 41, 114 };

    int head = 50;

    string direction = "left";

  

    SCAN(arr, head, direction);

  

    return 0;

}

**********************************************************************************************************************************************


Related Solutions

Python programming: can someone please fix my code to get it to work correctly? The program...
Python programming: can someone please fix my code to get it to work correctly? The program should print "car already started" if you try to start the car twice. And, should print "Car is already stopped" if you try to stop the car twice. Please add comments to explain why my code isn't working. Thanks! # Program goals: # To simulate a car game. Focus is to build the engine for this game. # When we run the program, it...
C++ Bank Account Error Fix, full code. I am using Dev-C++ to Compile and Execute. The...
C++ Bank Account Error Fix, full code. I am using Dev-C++ to Compile and Execute. The project is below, I have supplied the code and I'm getting an error in SavingsAccount.h file. 17   5   C:\Users\adam.brunell\Documents\Classes\C++\Week4\SavingsAccount.h   [Error] 'SavingsAccount::SavingsAccount(std::string, double, double)' is protected A.Assume i.SavingsAccount: Assume an Interest Rate of 0.03 ii.HighInterestSavings: Assume an Interest Rate of 0.05, Minimum Balance = $2500 iii.NoServiceChargeChecking: Assume an Interest Rate = 0.02, Minimum of Balance = $1000 iv.ServiceChargeChecking – Assume account service charge = $10,...
Write Verilog code using for 3:8 Decoders with Quartus-II CAD software?? and write code of Full...
Write Verilog code using for 3:8 Decoders with Quartus-II CAD software?? and write code of Full adder using 2 half adder ?
write a program for the microcontroller-msp430fr6989 using code composer studio not assembly language. write a code...
write a program for the microcontroller-msp430fr6989 using code composer studio not assembly language. write a code that transmits a single character and lights the red LED upon receiving that character. The board will "talk" to itself. The green LED should turn on whenever a message is sent and the LCD will display the message being received.
For the following program descriptions, write step by step pseudo code that shows you understand the...
For the following program descriptions, write step by step pseudo code that shows you understand the problem and what it takes to solve it. The first one is done for you as an example. Please answer the questions in the same format as the example problem below so it is the same. Example #1 Problem A customer is purchasing five items. Design a program where you collect the amount of each item, calculate the subTotal of the items, the tax...
Using the code below from “LStack.h” file, write the code for a main program that takes...
Using the code below from “LStack.h” file, write the code for a main program that takes as input an arithmetic expression. The program outputs whether the expression contains matching grouping symbols. For example, the arithmetic expressions { 25 + ( 3 – 6 ) * 8 } and 7 + 8 * 2 contains matching grouping symbols. However, the expression 5 + { ( 13 + 7 ) / 8 - 2 * 9 does not contain matching grouping symbols....
Write a code for simple racing game (using dots) on c program.
Write a code for simple racing game (using dots) on c program.
Using the provided code (found here), write a program using the main method where the user...
Using the provided code (found here), write a program using the main method where the user enters Strings and the program echoes these strings to the console until the user enters “quit”. When user quits the program should print out, “Goodbye”. You may assume that the case is ignored when the user enters, “quit”, so “quit”, “QUIT”, “Quit”,“qUiT”, etc. are all acceptable ways to end the program. The results should be printed out to the console in the following format:...
Complete the following in syntactically correct Python code. Write a program, using a for loop, that...
Complete the following in syntactically correct Python code. Write a program, using a for loop, that calculates the amount of money a person would earn over a period of time if his or her salary is 1 penny for the first day, 2 pennies for the second day, 4 pennies for the third day, and continues to double each day. 1.      The program should ask the user for the number of days the employee worked. 2.      Display a table showing the salary...
Write this program using an IDE. Comment and style the code according to the CS 200...
Write this program using an IDE. Comment and style the code according to the CS 200 Style Guide. Submit the source code files (.java) below. Make sure your source files are encoded in UTF-8. Some strange compiler errors are due to the text encoding not being correct. Monster collector is a game of chance, where the user tries to collect monsters by guessing the correct numbers between 1 and 5. If the user doesn't guess the incorrect number, you catch...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT