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,...
I already have the code of this program, I just want to know how to fix...
I already have the code of this program, I just want to know how to fix the code to Implement the 5th function (System.nanotime() and System.currentTimeMillis() methods) What Code does: Introduction Searching is a fundamental operation of computer applications and can be performed using either the inefficient linear search algorithm with a time complexity of O (n) or by using the more efficient binary search algorithm with a time complexity of O (log n). Task Requirements In this lab, you...
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.
Python 3 Fix the code so the program reads the file and see if the bar...
Python 3 Fix the code so the program reads the file and see if the bar code was already inputted 3 times if so, it ishows a warning indicating that the item was already tested 3 times Code: import tkinter as tk from tkcalendar import DateEntry from openpyxl import load_workbook from tkinter import messagebox from datetime import datetime window = tk.Tk() window.title("daily logs") window.grid_columnconfigure(1,weight=1) window.grid_rowconfigure(1,weight=1) # labels tk.Label(window, text="Bar code").grid(row=0, sticky="W", pady=20, padx=20) tk.Label(window, text="Products failed").grid(row=1, sticky="W", pady=20, padx=20) tk.Label(window,...
Design a 4-bit multiplier by using 4 bit full adder and write a verilog code.
Design a 4-bit multiplier by using 4 bit full adder and write a verilog code.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT