Starting from:

$29.99

 Assignment 6- Tasks with public members

Assignment 6 
This assignment introduces tasks with public members,direct communicationandhigh-leveltechniquesforstructuring complex interactions among tasks (versus monitor and semaphore structuring approaches). Use it to become familiar with these new facilities, and ensure you use these concepts in your assignment solution. WATCola is renown for its famous line of healthy soda pop, which come in the dazzling array of flavours: Blues Black-Cherry, Classic Cream-Soda, Rock Root-Beer, and Jazz Lime. The company recently won the contract to provide soda to vending machines on campus. The vending machines are periodically restocked by a WATCola truck making deliveries from the local bottling plant. This assignment simulates a simple concession service using the objects and relationships in Figure 1. (Not all possible communication paths are shown in the diagram.)
Delivery Truck
Machine1 Vending
Machine2 Vending
Machine3 Vending
Name Server
Bottling Plant
Office WATCard
Parent
Courier
Bank
Student1
Student2
Student3
Groupoff
Figure 1: Concession Service
The following constants are used to configure the simulation, and are read from a text file: SodaCost 2 # Manufacturer Suggested Retail Price (MSRP) per bottle NumStudents 2 # number of students to create MaxPurchases 8 # maximum number of bottles a student purchases NumVendingMachines 3 # number of vending machines MaxStockPerFlavour 5 # maximum number of bottles of each flavour in a vending machine MaxShippedPerFlavour 3 # maximum number of bottles of each flavour generated by the bottling # plant per production run TimeBetweenShipments 3 # length of time between shipment pickup GroupoffDelay 10 # length of time between new initializing gift cards ParentalDelay 2 # length of time between new deposits of funds NumCouriers 1 # maximum number of couriers in the pool
1
CS 343 - Assignment 6
2
Comments in the file (from # to the end-of-line), as well as blank lines, are ignored. The constants may appear in any order. Any number of spaces/tabs may appear around a constant name, value or comment. You may assume each constant appears in the configuration file, is syntactically correct, its value is within an appropriate range (i.e., no error checking is required), and only one constant is defined per line. You may have to modify the values in the provided sample file to obtain interesting results when testing. The following types and routines are required in the assignment (you may add only a public destructor and private/protected members):
1. struct ConfigParms { unsigned int sodaCost; // MSRP per bottle unsigned int numStudents; // number of students to create unsigned int maxPurchases; // maximum number of bottles a student purchases unsigned int numVendingMachines; // number of vending machines unsigned int maxStockPerFlavour; // maximum number of bottles of each flavour stocked unsigned int maxShippedPerFlavour; // number of bottles of each flavour in a shipment unsigned int timeBetweenShipments; // length of time between shipment pickup unsigned int groupoffDelay; // length of time between initializing gift cards unsigned int parentalDelay; // length of time between cash deposits unsigned int numCouriers; // number of couriers in the pool };
void processConfigFile( const char * configFile, ConfigParms & cparms );
Routine processConfigFile is called by the main program to read and parse the configuration file, and places the parsed values into the fields of the argument for output parameter cparms.
2. Task Student { void main(); public: Student( Printer & prt, NameServer & nameServer, WATCardOffice & cardOffice, Groupoff & groupoff, unsigned int id, unsigned int maxPurchases ); };
A Student’s function is to periodically buy some of their favourite soda from a vending machine (a bottle costs whatever the vending machine is charging). Each student is passed an id in the range [0, NumStudents) for identification. A student begins by selecting a random number of bottles to purchase [1, MaxPurchases], a random favourite flavour [0, 3], creates a WATCard via the WATCardOffice with a $5 balance, creates a gift card via the Groupoff with a value of SodaCost, and obtains the location of a vending machine from the name server. A student terminates after purchasing all the soda initially selected. Before each attempt to buy a soda (including the first), a student yields a random number of times in the range [1, 10]. A student then wants to buy a soda but may need to wait for money to be transferred either from the WATCardOffice to their WATCard or from Groupoff to their gift card. Once money is available on either card, the student can attempt to buy a bottle of soda from their current vending machine. Note, a giftcard future can only be used once, so it must be reset after use to prevent any further usage. If a courier has lost a student’s WATCard during a transfer (see WATCardOffice::Courier), the exception WATCardOffice::Lost is raised when the future value is accessed. In this case, the student must create a new WATCard via the WATCardOffice with a $5 balance, and re-attempt to buy a soda but without yielding as no call to buy has occurred. Note, a courier can lose a student’s WATCard during the transfer for the new WATCard so this issue can occur repeatedly. Once money is available, a purchase begins with a student calling a vending machine to begin a transaction. If the vending machine debits the WATCard and delivers a bottle of soda, the student drinks it and attempts another purchase. If the vending machine delivers a free bottle of soda, the student must watch an advertisement by yielding 4 times whiling drinking the free sode (there is no free lunch) and then attempts another purchase. If the vending machine indicates insufficient funds, a student transfers the current vending-machine soda-cost plus $5 to their WATCard via the WATCard office and attempts another purchase. If the vending machine is out of the student’s favourite flavour, the student must obtain a new vending machine from the name server and attempt another purchase. (Hence, a student may busy wait among vending machines until their specific soda appears from the bottling plant.) Watch out for the case of a student who only buys one soda using the gift card.
CS 343 - Assignment 6
3
3. class WATCard { WATCard( const WATCard & ) = delete; // prevent copying WATCard & operator=( const WATCard & ) = delete; public: typedef Future ISM<WATCard * FWATCard; // future watcard pointer WATCard(); void deposit( unsigned int amount ); void withdraw( unsigned int amount ); unsigned int getBalance(); };
The WATCard manages the money associated with a card. When a WATCard is created it has a $0 balance. The courier calls deposit after a funds transfer. A vending machine calls withdraw when a soda is purchased. A student and a vending machine call getBalance to determine the balance. FWATCard is a future pointer to a student’s WATCard for synchronizing access to the WATCard between the student and the courier.
4. Task WATCardOffice { struct Job { // marshalled arguments and return future Args args; // call arguments (YOU DEFINE “Args”) WATCard::FWATCard result; // return future Job( Args args ) : args( args ) {} }; Task Courier { ... }; // communicates with bank
void main(); public: Event Lost {}; // lost WATCard WATCardOffice( Printer & prt, Bank & bank, unsigned int numCouriers ); WATCard::FWATCard create( unsigned int sid, unsigned int amount ); WATCard::FWATCard transfer( unsigned int sid, unsigned int amount, WATCard * card ); Job * requestWork();
};
The WATCardOffice is an administrator task used by a student to transfer funds from their bank account to their WATCard to buy a soda. Initially, the WATCard office creates a fixed-sized courier pool with numCouriers courier tasks to communicate with the bank. (Additional couriers may not be created after the WATCardOffice begins.) A student performs an asynchronous call to create to create a “real” WATCard with an initial balance. A future WATCard is returned and sufficient funds are subsequentlyobtained from the bank (see Parenttask) via a courier to satisfy the create request. A student performs an asynchronous call to transfer when its WATCard indicates there is insufficient funds to buy a soda. A future WATCard is returned and sufficient funds are subsequentlyobtainedfrom the bank (see Parent task) via a courierto satisfy the transfer request. The WATCard officeis empoweredtotransferfundsfroma student’sbank-accounttoits WATCardbysendinga requestthrough a courier to the bank. Each courier task calls requestWork, blocks until a Job request is ready, and then receives the next Job request as the result of the call. As soon as the request is satisfied (i.e., money is obtained from the bank), the courier updates the student’s WATCard. There is a 1 in 6 chance a courier loses a student’s WATCard after the update. When the card is lost, the exception WATCardOffice::Lost is inserted into the future, rather than making the future available, and the current WATCard is deleted.
5. Monitor Bank { public: Bank( unsigned int numStudents ); void deposit( unsigned int id, unsigned int amount ); void withdraw( unsigned int id, unsigned int amount ); };
The Bank is a monitor, which behaves like a server, that manages student-account information for all students. Each student’s account initially starts with a balance of $0. The parent calls deposit to endow gifts to a specific student. A courier calls withdraw to transfer money on behalf of the WATCard office for a specific student. The courier waits until enough money has been deposited, which may require multiple deposits.
CS 343 - Assignment 6
4
6. Task Parent { void main(); public: Parent( Printer & prt, Bank & bank, unsigned int numStudents, unsigned int parentalDelay ); };
The Parent task periodically gives a random amount of money [$1, $3] to a random student. Before each gift is transferred, the parent yields for parentalDelay times (not random). The parent must check for a call to its destructor to know when to terminate. Since it must not block on this call, it is necessary to use a terminating Else on the accept statement. (Hence, the parent is busy waiting for the call to its destructor.)
7. Task Groupoff { void main(); public: Groupoff( Printer & prt, unsigned int numStudents, unsigned int sodaCost, unsigned int groupoffDelay ); WATCard::FWATCard giftCard(); };
The Groupoff task begins by accepting a call from each student to obtain a future gift-card. Then groupoff periodically puts a real WATCard with value SodaCost into a random future gift-card. A future gift-card is assigned only once. Before each future gift-card is assigned a real WATCard, groupoff yields for groupoffDelay times (not random). The groupoff loops until all the real WATCard’s are assigned to a future gift-card or a call to its destructor occurs. Since it must not block on the destructor call, it is necessary to use a terminating Else on the accept statement. (Hence, the groupoff is busy waiting for the call to its destructor.)
8. Task VendingMachine { void main(); public: enum Flavours { ... }; // flavours of soda (YOU DEFINE) Event Free {}; // free, advertisement Event Funds {}; // insufficient funds Event Stock {}; // out of stock for particular flavour VendingMachine( Printer & prt, NameServer & nameServer, unsigned int id, unsigned int sodaCost, unsigned int maxStockPerFlavour ); void buy( Flavours flavour, WATCard & card ); unsigned int * inventory(); void restocked(); Nomutex unsigned int cost(); Nomutex unsigned int getId(); };
A vending machine’s function is to sell soda to students at some cost. Each vending machine is passed an id in the range [0, NumVendingMachines) for identification, MSRP price for a bottle of soda, and the maximum number of bottles of each flavour in a vending machine. A new vending machine is empty (no stock) and begins by registering with the name server. A student calls buy to obtain one of their favourite sodas. If the student has insufficient funds to purchase the soda or the specified soda is unavailable, exceptions Funds or Stock are raised, respectively; otherwise, the student’s WATCard is debited by the cost of a soda. However, there is a 1 in 5 chance the soda is free, if the student watches an advertisement, which is indicated by raising exception Free. (A flag variable is necessary to know when to raise Funds or Stock on the correct task stack.) Periodically, the truck comes by to restock the vending machines with new soda from the bottling plant. Restockingis performedin two steps. The truck calls inventoryto returna pointerto an array containingthe amount of each kind of soda currently in the vending machine. The truck uses this information to transfer into each machine as much of its stock of new soda as fits; for each kind of soda, no more than MaxStockPerFlavour per flavour can be added to a machine. If the truck cannot top-up a particular flavour, it transfers as many bottles as it has (which could be 0). After transferring new soda into the machine by directly modifying the array passed from inventory, the truck calls restocked to indicate the operation is complete. The vending machine cannot accept buy calls during restocking. The cost member returns the cost of purchasing a soda for this machine. The
CS 343 - Assignment 6
5
getId member returns the identification number of the vending machine. You define the public type Flavours to represent the different flavours of soda.
9. Task NameServer { void main(); public: NameServer( Printer & prt, unsigned int numVendingMachines, unsigned int numStudents ); void VMregister( VendingMachine * vendingmachine ); VendingMachine * getMachine( unsigned int id ); VendingMachine ** getMachineList(); };
The NameServer is an administrator task used to manage the vending-machine names. The name server is passed the number of vending machines, NumVendingMachines, and the number of students, NumStudents. It begins by logically distributing the students evenly across the vending machines in a round-robin fashion. That is, student id 0 is assigned to the first registered vending-machine, student id 1 is assigned to the second registered vending-machine,etc., until there are no more registered vending-machines,and then start again with the first registered vending-machine. Vending machines call VMregister to register themselves so students can subsequently locate them. A student calls getMachine to find a vending machine, and the name server must cycle through the vending machines separately for each student starting from the initial position via modulo incrementing to ensure a student has a chance to visit every machine. The truck calls getMachineList to obtain an array of pointers to vending machines so it can visit each machine to deliver new soda. All vending machines are registered before being given out.
10. Task BottlingPlant { void main(); public: Event Shutdown {}; // shutdown plant BottlingPlant( Printer & prt, NameServer & nameServer, unsigned int numVendingMachines, unsigned int maxShippedPerFlavour, unsigned int maxStockPerFlavour, unsigned int timeBetweenShipments ); void getShipment( unsigned int cargo[] ); };
The bottling plant periodically produces random new quantities of each flavour of soda, [0, MaxShippedPerFlavour] per flavour. The bottling plant is passed the number of vending machines, NumVendingMachines, the maximum number of bottles of each flavour generated during a production run and subsequently shipped, MaxShippedPerFlavour, the maximum number of bottles of each flavour in a vending machine MaxStockPerFlavour, and the length of time between shipment pickups by the truck, TimeBetweenShipments. It begins by creating a truck, performing a production run, and waiting for the truck to pickup the production run. The truck then distributes these bottles to initialize the registered vending machines. To simulate a production run of soda, the bottling plant yields for TimeBetweenShipments times (not random). The truck calls getShipment to obtain a shipment from the plant (i.e., the production run), and the shipment is copied into the cargo array passed by the truck. getShipment throws the exception Shutdown if the bottling plant is closing down, and no shipment is copied into the cargo array passed by the truck. A flag variable is necessary to know when to raise Shutdown on the correct task stack.) The bottling plant does not start another production run until the truck has picked up the current run.
11. Task Truck { void main(); public: Truck( Printer & prt, NameServer & nameServer, BottlingPlant & plant, unsigned int numVendingMachines, unsigned int maxStockPerFlavour ); };
The truck moves soda from the bottling plant to the vending machines. The truck is passed the number of vending machines, numVendingMachines, and the maximum number of bottles of each flavour in a vending machine maxStockPerFlavour. The truck begins by obtaining the location of each vending machine from the name server. Before each shipment from the bottling plant, the truck yields a random number of times [1, 10]
CS 343 - Assignment 6
6
to get a coffee from Tom Hortons. The truck then calls BottlingPlant::getShipment to obtain a new shipment of soda; any soda still on the truck is thrown away as it is past its due date. If the bottling plant is closing down, the truck terminates. To ensure fairness, the vending machines are restocked in cyclic order starting at the vending machine after the last machine the truck restocked, until there is no more soda on the truck or the truck has made a complete cycle of all the vending machines; so there is no guarantee each vending machine is completely restocked or the entire complement of vending machines is restocked or all the soda on the truck is used. The truck can only restock up to MaxStockPerFlavour for each flavour in each vending machine (see VendingMachine task).
12. Monitor / Cormonitor Printer { public: enum Kind { Parent, Groupoff, WATCardOffice, NameServer, Truck, BottlingPlant, Student, Vending, Courier }; Printer( unsigned int numStudents, unsigned int numVendingMachines, unsigned int numCouriers ); void print( Kind kind, char state ); void print( Kind kind, char state, int value1 ); void print( Kind kind, char state, int value1, int value2 ); void print( Kind kind, unsigned int lid, char state ); void print( Kind kind, unsigned int lid, char state, int value1 ); void print( Kind kind, unsigned int lid, char state, int value1, int value2 ); };
All output from the program is generated by calls to a printer, excluding error messages. The printer generates output like that in Figure 2. Each column is assigned to a particular kind of object. There are 9 kinds of objects: parent, groupoff, WATCard office, name server, truck, bottling plant, student, vending machine, and courier. Student, vending machine, and courier have multiple instances. For the objects with multiple instances, these objects pass in their local identifier [0,N) when printing. Each kind of object prints specific information in its column:
• The parent prints the following information: State Meaning Additional Information S starting D s,g deposit gift student s receiving gift, amount of gift g F finished • The groupoff prints the following information: State Meaning Additional Information S starting D g deposit gift amount of gift g F finished • The WATCard office prints the following information: State Meaning Additional Information S starting W request work call complete C s,a create call complete student s, transfer amount a T s,a transfer call complete student s, transfer amount a F finished • The name server prints the following information: State Meaning Additional Information S starting R v register vending machine vending machine v registering N s,v new vending machine student s requesting vending machine, new vending machine v F finished
CS 343 - Assignment 6
7
% soda soda.config 64466 Parent Gropoff WATOff Names Truck Plant Stud0 Stud1 Mach0 Mach1 Mach2 Cour0 ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* S S S S S D0,1 R0 S2 D0,1 R1 S2 D1,3 R2 S S1,3 S2 D0,2 C0,5 N0,0 S G11 V0 S2,4 t0,5 D0,1 W V1 L0 C1,5 N1,1 P11 d0,11 U0,9 D0,1 W D0,0 P r t1,5 D0,3 G11 R D1,2 P11 d1,11 U1,9 D0,1 C0,5 D1,0 P L r T1,5 t0,5 D0,2 D2 W P4 G4 R T0,5 d2,4 U2,16 D0,3 D2,0 P B1,3 B2,3 B1,2 B2,2 r D1,1 G6 R D0,2 D1,2 P6 d0,6 U0,4 D1,2 D2 D0,0 P r D1,2 F G5 G2,0 R D1,3 A1,3 B2,1 D0,3 P5 d1,5 U1,6 D1,1 D1,0 P r D0,3 G3 B2,1 R D1,3 P3 d2,3 U2,13 D1,1 D2,0 P B2,1 r D1,1 G7 G1,0 R D1,3 P7 P F B1,2 d0,7 U0,3 D0,2 T1,7 D0,4 r t1,7 D0,2 W G9 B2,6 R T1,7 D0,1 d1,4 F B2,0 U1,7 D0,1 D1,3 r d2,3 U2,10 D1,1 D2,0 R r D0,1 F R D1,2 F D1,3 F D0,1 F D1,2 F D1,3 F D1,1 F D0,3 F F ***********************
Figure 2: WATCola : Example Output
CS 343 - Assignment 6
8
• The truck prints the following information: State Meaning Additional Information S starting P a picked up shipment total amount a of all sodas in the shipment d v,r begin delivery to vending machine vending machine v, total amount remaining r in the shipment U v,b unsuccessfully filled vending machine vending machine v, total number of bottles b not replenished D v,r end delivery to vending machine vending machine v, total amount remaining r in the shipment F finished States d and D are printed for each vending machine visited during restocking. • The bottling plant prints the following information: State Meaning Additional Information S starting G b generating soda bottles b generated in production run P shipment picked up by truck F finished • A student prints the following information: State Meaning Additional Information S f,b starting favourite soda f, number of bottles b to purchase V v selecting vending machine vending machine v selected G f,b gift-card soda soda flavour f purchased, giftcard balance b a f,b free soda, advertisement soda flavour f purchased, giftcard balance b B f,b bought soda soda flavour f purchased, WATCard balance b A f,b free soda, advertisement soda flavour f purchased, WATCard balance b L WATCard lost F finished • A vending machine prints the following information: State Meaning Additional Information S c starting cost c per bottle r start reloading by truck R complete reloading by truck B f,r student bought a soda soda flavour f purchased, amount remaining r of this flavour F finished • A courier prints the following information: State Meaning Additional Information S starting t s,a start funds transfer student s requesting transfer, amount a of transfer L s lost WATCard card student s requesting transfer T s,a complete funds transfer student s requesting transfer, amount a of transfer F finished
Information is buffered until a column is overwritten for a particular entry, which causes the buffered data to be flushed. If thereis no new stored informationfora columnsince the last bufferflush, an emptycolumnis printed. After an object has finished, no further output appears in that column. All output spacing can be accomplished using the standard 8-space tabbing. Buffer any information necessary for printing in internal representation; do not build and store strings of text for output.
The program main starts by calling processConfigFile to read and parse the simulation configurations. It then creates in order the printer, bank, parent, WATCard office, groupoff, name server, vending machines, bottling plant, and students. The truck is created by the bottling plant; the couriers are created by the WATCard office. The program terminates once all of the students have purchased their specified number of bottles. Note, there is one trick in closing down the system: delete the bottling plant before deleting the vending machines to allow the truck to complete its final deliveries to the vending machines; otherwise, a deadlock can occur. The executable program is named soda and has the following shell interface:
CS 343 - Assignment 6
9
soda [ config-file [ Seed ] ] config-file is thetext(formatted)file containingthe configurationconstants. Ifunspecified,usethefile namesoda.config. Seed is the seed for the random-numbergenerator and must be greater than 0. If the seed is unspecified, use a random value like the process identifier (getpid) or current time (time), so each run of the program generates different output. Use the monitor MPRNG to safely generate random values. Note, because of the non-deterministic execution of concurrent programs, multiple runs with a common seed may not generate the same output. Nevertheless, shorts runs are often the same so the seed can be useful for testing. Check all command arguments for correct form (integers) and range; print an appropriate usage message and terminate the program if a value is missing or invalid. Do not try to code this program all at once. Write each task separately and test it before putting the pieces together. Play with the sample executable to familiarize yourself with the system before starting to write code.
Submission Guidelines
This assignment should be done by a team of two people because of its size. Both people receive the same grade (no exceptions). Only one member of a team submits the assignment. The instructor and/or instructional-coordinator does not arbitrate team disputes; team members must handle any and all problems. Please follow these guidelines carefully. Review the Assignment Guidelines and C++ Coding Guidelines before starting each assignment. Each text file, i.e., *.*txt file, must be ASCII text and not exceed 750 lines in length, where a line is 120 characters. Programs should be divided into separate compilation units, i.e., *.{h,cc,C,cpp} files, where applicable. Use the submit command to electronically copy the following files to the course account.
1. *.{h,cc,C,cpp} – code for the assignment. Program documentation must be present in your submitted code. No user or system documentation is to be submitted for this question.
2. soda.testdoc – test documentation for the assignment, which includes the input and output of your tests. Poor documentation of how and/or what is tested can results in a loss of all marks allocated to testing.
3. group.txt – give the userid of each group member, with one userid per line (i.e., 2 lines in this file), e.g.:
sjholmes jjwatson
Do not submit this file if you are working by yourself.
4. Makefile – construct a makefile with target soda, which creates the executable file soda from source code in the makefile directory when the command make soda is issued. This Makefile must be submitted with the assignment to build the program,so it must be correct. Use the web tool Request Test Compilation to ensure you have submittedthe appropriatefiles, yourmakefile is correct, and yourcode compiles in the testing environment.
Follow these guidelines. Your grade depends on it!

More products