Title: Priority Queue
1Priority Queue
- A priority queue is an ADT with the property that
only the highest-priority element can be accessed
at any time. When there are several elements of
the highest priority the priority queue acts like
a queue of those elements. - Every element is a key-value pair, where the key
is the priority and the value is the data.
2Priority Queue API
CLASS priority_queue Constructors
ltpqueue.hgt
priority_queue() Create an empty
priority_queue.
CLASS priority_queue Operations
ltpqueue.hgt
bool empty() const Check whether the
priority_queue is empty. Return true if it is
empty, false otherwise. void pop() Remove
the item with highest priority from the priority
queue. Precond The priority queue is not
empty. Postcond The priority queue has one
fewer elements. void push(const T item)
Insert the argument item into the priority
queue. Postcond The priority queue contains
a new item.
3Priority Queue API
CLASS queue Operations
ltpqueue.hgt
T front() Return a reference to the value
of the item that has the highest priority.
Precond The priority queue is not empty. const
T front() Constant version of front. int
size() const Return the number of items in
the priority queue.
4An implementation for priority queues
- A priority queue can be implemented as an ordered
array. - The head of the list is the element of highest
priority. - New items are added after all items of the same
priority and before all items of lower priority.
5An implementation for priority queues
- A priority queue can be implemented as an
unordered array. - New items are added an the end of the queue.
- The list is searched for the first element with
the highest priority, which is deleted, by moving
other elements below it up.
6An implementation for priority queues
- A heap can be used to implement a priority queue.
- A heap is an complete tree where the root is
larger than all other nodes in the tree, and this
property holds for all subtrees in the tree.
7Example of a heap
82
69
58
15
14
26
45
32
18
6
Heaps will be discussed in more detail later in
the semester
8Time Driven Simulation
- Simulating the arrival and departure of people at
a bank, or printer jobs in the print queue. - The arrival of a particular person, or job is and
event. - The departure or completion of a person's
business or a job is an event. - All events occur in a sequence based on the time
of their occurrence.
9Time-Driven Simulation Example
- Jobs arrive at a printer at a variable rate
between every 2 to 10 minute. Each job may
require between 3 and 100 pages to be printed.
There are two printers available. One which
prints at a rate of 5 pages per minute and the
other prints at a rate of 7 pages per minute.
Run a simulation of this situation for a period
of 100 minutes, and determine how many pages each
printer printed and what the average wait time is
per job, and when the last job finishes printing.
If both printers are free, a job will select the
faster printer, otherwise the printer for a
particular job is selected based on which printer
will be free first.
10Generation of job parameters
- A random number generator is used to determine
the arrival time and number of pages associated
with each job. - When a job is generated, the arrival time for the
next job is calculated. - a random number between 0 and 8 is produced an
the next arrival time is the current time 2
the random number. - The number of pages for the current job is
determined in a similar manner
11The simulation process
- First jobs are generated and placed on the
priority queue until the next job to arrive has a
time later than the simulation end time. - Then the priority queue is processed with an
event being removed from the priority queue based
on the time stamp. When an arrival event is
processed, it will select a printer, update the
printer availability and place a departure event
on the priority queue. Departure events will
update the printer statistics and availability
info.
12Event ADT
- The data for an event consists of
- the time stamp
- the type of event (Arrival or Departure)
- the number of pages to be printed
- the printer to be used
- the wait time before the job starts printing
- Operations include
- Constructor
- Methods to retrieve the various data members.
- Methods to set the various data members
- Method to print events to file
- Method to compare events based on time stamp
13Event.H
- class event
- private
- time ShipTime
- char EventType
- int Pages
- int PrinterUsed
- time StartPrintingTime
-
14Event.H - cont.
- public
- // Default constructor
- event(time initialTimetime(), char eTypeA,
- int pg0, int prntr1, time
endTimetime()) - // setInitialTime changes ShipTime of self to ST
- // Precond ST is greater than or equal to 0.
- // Postcond ShipTime has value of ST
- void setInitialTime(time ST)
-
15Event.H - cont.
- // setEventType changes EventType of self to T
- // Precond T is either A or D
- // Postcond EventType of self is changed
to T - void setEventType(char T)
- // setPages changes Pages of self to P
- // Precond P must be greater than 0
- // Postcond Pages of self is changed to P
- void setPages(int P)
-
16Event.H - cont.
- // setPrinter changes PrinterUsed of self to P
- // Precond P is between 0 and 9 inclusive
- // Postcond PrinterUsed of self is changed
to P - void setPrinter(int P)
- // setStartPr changes StartPrintingTime of self
to SP - // Precond SP is greater than or equal to 0
- // Postcond StartPrintingTime is set to SP
- void setStartPr(time SP)
17Event.H - cont.
- // getInitTime returns ShipTime
- time getInitTime(void)
- // arrive returns true if EventType is A and
false - // otherwise
- bool arrive(void)
- // depart returns true if EventType is D and
false - // otherwise
- bool depart(void)
- // getPages returns value of Pages
- int getPages(void)
18Event.H - cont.
- // getPrinter returns value of PrinterUsed
- int getPrinter(void)
- // getStartPr returns StartPrintingTime
- time getStartPr(void)
- // Print will print an event to an output file
- // Precond The file must be open for output
- void print(ofstream ostr)
19Event.H - cont.
- // Returns true if the ShipTime of self is
greater - // than the ShipTime of rhs, and false
otherwise. - bool operatorgt (event rhs)
- // Returns true if the ShipTime of self is
equal to - // the ShipTime of rhs, and false otherwise.
- bool operator (event rhs)
- // Returns true if the ShipTime of self is less
than - // the ShipTime of rhs, and false otherwise.
- bool operatorlt (event rhs)
-
-
20Printer.H
class printer private // pages per
minute int Speed // number of pages
printed int Total pages //
time when the printer is next free time WhenFre
e
21Printer.H - cont.
- // Default constructor - initializes printer to
0 pages - // printed and currently free, sets Speed to
- // pgPerMinute
- printer(int pgPerMin5)
- // setSpeed changes Speed of self to pgPerMin
- // Precond pgPerMin is greater than or equal
to 0 - // Postcond Speed is set to pgPerMin
- void setSpeed(int pgPerMin)
-
22Printer.H - cont.
- // setWhenFree changes WhenFree of self to TWF
- // Precond TWF is greater than or equal to 0
- // Postcond WhenFree is set to TWF
- void setWhenFree(time TWF)
- // IncrTotalPages adds currPg to TotalPages
- // Precond currPg is greater than 0
- // Postcond TotalPages is increased by
currPg - void incrTotalPages(int currPg)
- // getSpeed returns Speed of self as pages per
min. - int getSpeed(void)
23Printer.H - cont.
// getTotalPages returns TotalPages printed for
self int getTotalPages (void) // getWhenFree
returns WhenFree for self time
getWhenFree(void)
24Simulator.H
class simulator private // minimum time
simulation runs time simulationLength
// of printers for simulation int
numberOfPrinters // number of jobs
processed int jobCnt // total time jobs
have waited for a printer time waitCnt //
current time in simulation, records time
simulation stop time currTime // printers
used for simulation vectorltprintergt
prtlist // priority queue for
simulation priority_queue pQ // file to log
simulation actions ostream log
25ADT Simulator Specifications
- public
- // Default constructor - Initializes the
summary variables for - // the simulation, obtains from the user the
parameters for the - // simulation, and initializes the priority
queue with the print // jobs that come in over
the specified time. - simulator(void)
- // Simulates execution of all events in the
priority queue. - // Postcond priority queue is empty, status
variables hold - // result of simulation
- void runSimulation(void)
- // Prints the results of the simulation to
screen. - // Precond runSimulation must have been
executed. - void printStatistics(void)
26Process control diagram for the printer
simulation problem
main
Simulator
Priority Queue
Printer
Random Number
ofstream
Event
Time
Time
27Main Program for Simulation
- include ltiostream.hgt
- include "simulator.h"
- include d_random.h"
- int main()
- simulator PrintExample
- PrintExample.runSimulation()
- PrintExample.printStatistics()
- return 0
28Simulator Constructor
- simulatorsimulator()
- float currTime
- int arriveLow, arriveHigh
- int pageLow, pageHigh
- randomNumber rNum
- // Get simulation parameters from user
- . . .
- // Initialize each printer
- . . .
- // Initialize statistics variables
- . . .
- // Open the log file
- log.open("logfile.dat")
- // Initialize the priority queue with arriving
jobs.
29Run Simulator Method
- void simulatorrunSimulation()
- event currEvent
- event newEvent
- int printerNumber
- float JobExecutionTime
- // Initialization
- newEvent.setEventType('D')
30- while (!pQ.empty())
- // Delete next item from pq and print it to
the log. - currEvent pq.front()
- pq.pop()
- log ltlt "\nDelete\t"
- currEvent.print(log)
-
- if (currEvent.arrive())
- // build Depart Event for printer job
- . . .
- // Insert new depart event onto the pq and
print it to the log. - . . .
-
- else if (currEvent.depart())
- // Update statistics
- . . .
-
-
- log.close()