Question

Write a cpp program

The Server Class The Server class is simply there to emulate a server in the elient-server model/arehitecture and includes the following functions: Server(string filename, int threads) - This is the constretor and l read in a file specified by filename and split the content of the file into threads number of pieces and store it in an array called ascii. Keep nd that the indexes start from 0 and not . Serve The destructor which deletes the dynamically allocated ascii array. getPiece(int piece) - A method which returns the piece (a string) frt array specified by piece. asii In this task you arrequired to implement a number of functions in the file deadlock.cpp The implementation of these functions should provide you with two deadlock situa tions. You will need to use threads when implementing these functions. You may use high level C threads OR pthreads for this purpose. You will also need to use some locking mechanism to achieve mutual exclusion between threads. The methods you need to implement are as follows: 1. printToScreen(string toScreen) - Implement this function to deal with the race condition on stdout (i.e. printing to the screen). If multiple threads try and output to the screen concurently, much of the text being output will collide with each other and create a line, or multiple lines, of difficult to interpret text. This is what is mant by the race condition on stdout 2. output(string toPrint) - This funetion writes the string toPrint to a file called deadlock.txt. Bofore opening the file you will need to output, to the screen, the string Opening... and before writing to the file output, to the screen, the string Writing...

Server.h

#ifndef SERVER_H
#define SERVER_H

#include
#include
#include
#include

using namespace std;

class Server
{
public:
   Server();
   Server(string, int);
   ~Server();
   string getPiece(int);
private:
   string *ascii;
   mutex access;
};

#endif

--------------------------------------------------------------------------------------------------------------------------

Server.cpp

#include "Server.h"
#include
#include

Server::Server(){}

Server::Server(string filename, int threads)
{
   vector loaded;
   ascii = new string[threads];
   ifstream in;
   string line;
   in.open(filename);
   if (!in.is_open())
   {
       cout << "Could not open file " << filename << endl;
       exit(1);
   }
   while(!in.eof())
   {
       getline(in, line);
       loaded.push_back(line);
   }
   in.close();

   int step = loaded.size()/threads;
   string piece = "";

   for (int i = 0; i < threads; ++i)
   {
       for (int j = step*i; j < ((step*i) + step); ++j)
       {
           if (j + 1 < loaded.size())
               piece += loaded.at(j) + "\n";
           else
               piece += loaded.at(j);
       }
       ascii[i] = piece;
       piece = "";
   }
}

Server::~Server()
{
   delete []ascii;
}

string Server::getPiece(int piece)
{
   srand(time(NULL));
   if (rand()/static_cast(RAND_MAX) > 0.6)
       throw "500 Internal Server Error";
   cout << "Getting piece number " << piece << endl;
   string toReturn = ascii[piece];
   return toReturn;
}

--------------------------------------------------------------------------------------------------------------------------

deadlock.cpp

#include
#include
#include "../Server.h"

using namespace std;

Server *server;

void printToScreen(string toPrint)
{
   /* Implement this function so that printing from each thread to stdout (i.e. using cout) doesn't clash with each other. */
}

void print(string out)
{
   /* Output to file called deadlock.txt */
}

void lock(int choice)
{
   /* Based on the choice, lock either the server or printer */
}

void unlock(int choice)
{
   /* Based on the choice, unlock either the server or printer */  
}

void spin(int index)
{
   /* Wait until it is "index's" turn to write to the file. */
}

void evenThread(int index)
{
   try
   {
       spin(index);

       lock(0); // server
       printToScreen("Thread " + to_string(index) + ": Lock acquired for Server\n");
       string piece = server->getPiece(index);

       print(piece);
      
       unlock(0);
       printToScreen("Thread " + to_string(index) + ": Lock released for Server\n");
      
       unlock(1); // printer
       printToScreen("Thread " + to_string(index) + ": Lock released for Printer\n");
   }
   catch (const char *msg)
   {
       cerr << msg << endl;
   }
}

void oddThread(int index)
{
   try
   {
       lock(0); // server
       printToScreen("Thread " + to_string(index) + ": Lock acquired for Server\n");
       string piece = server->getPiece(index);

       spin(index);
       print(piece);
      
       unlock(0);
       printToScreen("Thread " + to_string(index) + ": Lock released for Server\n");
      
       unlock(1); // printer
       printToScreen("Thread " + to_string(index) + ": Lock released for Printer\n");
   }
   catch (const char *msg)
   {
       cout << msg << endl;
   }
}

int main(int argc, char const *argv[])
{
   if (/*filename argument*/ != "" && /*thread count argument*/ != 0)
   {
       server = new Server(/*filename argument*/, /*thread count argument*/);
      
       /* Fill in the main function code here */
      
       delete server;
   }
   else
   {
       cout << "Please enter a file name and the number of threads to use!" << endl;
   }

   return 0;
}

---------------------------------------------------------------------------------------------------------------------------

batman.ascii

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

0 0
Add a comment Improve this question Transcribed image text
Answer #1

mutex server;

mutex printer;

condition_variable cv;

mutex thread_no;

mutex screen;

Static int thread_run = 0;

void printToScreen(string toPrint)

{

screen.lock();

cout<< toPrint << endl;

screen.unlock();

}

void print(string out)

{

ofStream myfile;

printToScreen("Opening...");

myfile.open("deadlock.txt",ios_base::app);

printToScreen("Writing...");

myfile << out;

myfile.close();

}

void lock(int choice)

{

if(choice==0){

server.lock();

}

elseif(choice==1){

printer.lock();

}

}

void unlock(int choice)

{

if(choice==0){

server.unlock();

}

elseif(choice==1){

printer.unlock();

}

}

void spin(int index)

{

unique_lock<mutex> lck(thread_no);

while(index!=thread_run){

cv.wait(lck);

}

lock(1);

thread_run++;

cv.notifyAll();

}

int main(int argc, char const *argv[])

{

thread mythreads[argv[2]];

if (argv[1] != "" && argv[2] != 0)

{

server = new Server(argv[1], argv[2]);

  

for(i=0;i<argv[2];i++){

if(i%2==0){

mythreads[i]=thread(evenThread,i);

}

else {

mythreads[i]=thread(oddThread,i);

}

}

for(i=0;i<argv[2];i++){

mythreads[i].join();

}

  

delete server;

}

else

{

cout << "Please enter a file name and the number of threads to use!" << endl;

}

return 0;

}

Add a comment
Know the answer?
Add Answer to:
Write a cpp program Server.h #ifndef SERVER_H #define SERVER_H #include #include #include #include using namespace std;...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write a psuedocode for this program. #include <iostream> using namespace std; string message; string mappedKey; void...

    Write a psuedocode for this program. #include <iostream> using namespace std; string message; string mappedKey; void messageAndKey(){ string msg; cout << "Enter message: "; getline(cin, msg); cin.ignore(); //message to uppercase for(int i = 0; i < msg.length(); i++){ msg[i] = toupper(msg[i]); } string key; cout << "Enter key: "; getline(cin, key); cin.ignore(); //key to uppercase for(int i = 0; i < key.length(); i++){ key[i] = toupper(key[i]); } //mapping key to message string keyMap = ""; for (int i = 0,j...

  • #include <fstream> #include <iostream> #include <cstdlib> using namespace std; // Place charcnt prototype (declaration) here int...

    #include <fstream> #include <iostream> #include <cstdlib> using namespace std; // Place charcnt prototype (declaration) here int charcnt(string filename, char ch); int main() { string filename; char ch; int chant = 0; cout << "Enter the name of the input file: "; cin >> filename; cout << endl; cout << "Enter a character: "; cin.ignore(); // ignores newline left in stream after previous input statement cin.get(ch); cout << endl; chcnt = charcnt(filename, ch); cout << "# of " «< ch« "'S:...

  • In C++ ***//Cat.h//*** #ifndef __Cat_h__ #define __Cat_h__ #include <string> using namespace std; struct Cat { double...

    In C++ ***//Cat.h//*** #ifndef __Cat_h__ #define __Cat_h__ #include <string> using namespace std; struct Cat { double length; double height; double tailLength; string eyeColour; string furClassification; //long, medium, short, none string furColours[5]; }; void initCat (Cat&, double, double, double, string, string, const string[]); void readCat (Cat&); void printCat (const Cat&); bool isCalico (const Cat&); bool isTaller (const Cat&, const Cat&); #endif ***//Cat.cpp//*** #include "Cat.h" #include <iostream> using namespace std; void initCat (Cat& cat, double l, double h, double tL, string eC,...

  • Please complete Part 1. The code is also below: #include <pthread.h> #include <iostream> using namespace std;...

    Please complete Part 1. The code is also below: #include <pthread.h> #include <iostream> using namespace std; void *PrintHello(void *arg) { int actual_arg = *((int*) arg); cout << "Hello World from thread with arg: " << actual_arg << "!\n"; return 0; } int main() { pthread_t id; int rc; cout << "In main: creating thread \n"; int t = 23; rc = pthread_create(&id, NULL, PrintHello, (void*) &t); if (rc){ cout << "ERROR; return code from pthread_create() is " << rc <<...

  • #include #include #include #include #include #include #include using namespace std; const int MAX = 26; string...

    #include #include #include #include #include #include #include using namespace std; const int MAX = 26; string addRandomString(int n) {    char alphabet[MAX] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g',    'h', 'i', 'j', 'k', 'l', 'm', 'n',    'o', 'p', 'q', 'r', 's', 't', 'u',    'v', 'w', 'x', 'y', 'z' };    string res = "";    for (int i = 0; i < n; i++)    res = res + alphabet[rand() % MAX];    return res;...

  • CODES: main.cpp #include <iostream> #include <string> #include "ShoppingCart.h" using namespace std; char PrintMenu() { char answer;...

    CODES: main.cpp #include <iostream> #include <string> #include "ShoppingCart.h" using namespace std; char PrintMenu() { char answer; cout << "MENU" << endl; cout << "a - Add item to cart" << endl; cout << "d - Remove item from cart" << endl; cout << "c - Change item quantity" << endl; cout << "i - Output items' descriptions" << endl; cout << "o - Output shopping cart" << endl; cout << "q - Quit" << endl << endl; while (true) {...

  • #include <iostream> #include <string> #include <fstream> #include <sstream> using namespace std; struct transition{ // transition structure...

    #include <iostream> #include <string> #include <fstream> #include <sstream> using namespace std; struct transition{ // transition structure char start_state, to_state; char symbol_read; }; void read_DFA(struct transition *t, char *f, int &final_states, int &transitions){ int i, j, count = 0; ifstream dfa_file; string line; stringstream ss; dfa_file.open("dfa.txt"); getline(dfa_file, line); // reading final states for(i = 0; i < line.length(); i++){ if(line[i] >= '0' && line[i] <= '9') f[count++] = line[i]; } final_states = count; // total number of final states // reading...

  • #include<iostream> #include<string> #include<iomanip> using namespace std; /* ********* Class Car ************* ********************************* */ class Car {...

    #include<iostream> #include<string> #include<iomanip> using namespace std; /* ********* Class Car ************* ********************************* */ class Car { private: string reportingMark; int carNumber; string kind; bool loaded; string choice; string destination; public: Car() { reportingMark = ""; carNumber = 0; kind = "Others"; loaded = 0; destination = "NONE"; } ~Car() { } void setUpCar(string &reportingMark, int &carNumber, string &kind, bool &loaded, string &destination); }; void input(string &reportingMark, int &carNumber, string &kind, bool &loaded,string choice, string &destination); void output(string &reportingMark, int &carNumber,...

  • PLEASE HELP WITH THE FIX ME'S #include #include #include #include "CSVparser.hpp" using namespace std; //==...

    PLEASE HELP WITH THE FIX ME'S #include #include #include #include "CSVparser.hpp" using namespace std; //============================================================================ // Global definitions visible to all methods and classes //============================================================================ // forward declarations double strToDouble(string str, char ch); // define a structure to hold bid information struct Bid { string bidId; // unique identifier string title; string fund; double amount; Bid() { amount = 0.0; } }; //============================================================================ // Linked-List class definition //============================================================================ /** * Define a class containing data members and methods to *...

  • Need to implement Account.cpp and AccountManager.cpp code //Account.hpp #ifndef _ACCOUNT_HPP_ #define _ACCOUNT_HPP_ #include <string> using std::string;...

    Need to implement Account.cpp and AccountManager.cpp code //Account.hpp #ifndef _ACCOUNT_HPP_ #define _ACCOUNT_HPP_ #include <string> using std::string; class Account { public: Account(); Account(string, double); void deposit(double); bool withdraw(double); string getName() const; double getBalance() const; private: string name; double balance; }; #endif ////////////////////////////////////////////// //AccountManager.hpp #ifndef _ACCOUNT_MANAGER_HPP_ #define _ACCOUNT_MANAGER_HPP_ #include "Account.hpp" #include <string> using std::string; class AccountManager { public: AccountManager(); AccountManager(const AccountManager&); //copy constructor void open(string); void close(string); void depositByName(string,double); bool withdrawByName(string,double); double getBalanceByName(string); Account getAccountByName(string); void openSuperVipAccount(Account&); void closeSuperVipAccount(); bool getBalanceOfSuperVipAccount(double&) const;...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT