Использование кучи и блока управления процессом для создания симулятора планирования

Поэтому я пытаюсь создать симулятор планирования на основе значения приоритета. У меня есть заголовок блока управления процессом, показанный ниже, в котором есть все необходимые значения для планирования. Мой вопрос заключается в том, что, когда я сохраняю свою печатную плату в кучу в своем основном цикле, я не знаю, как организовать кучу по значению приоритета, при этом -20 является первым по приоритету, а 19 — последним. Кажется, что когда я сохраняю печатную плату в куче, она не будет организована по каким-либо значениям и будет иметь случайный вывод, когда я решу удалить или посмотреть значение. Любая помощь будет оценена! (Если вам нужна дополнительная информация, просто прокомментируйте!)

Heap.h:

    #include <string>
#include <iostream>
#include <stdexcept>
#include <vector>

#ifndef HEAP_H
#define HEAP_H

using namespace std;

/**
* This class reports Heap exceptions.
*/
class HeapException
{
private:
/**
* Reason for the exception
*/
string message;
public:
/**
* Constructs a HeapException
* @param aMessage why the exception occurred
*/
HeapException(const string& aMessage)
{
message = aMessage;
}
/**
* Gives a reason for this exception
* @return why the this exception occurred
*/
string what() const
{
return message;
}
};

template <typename E>
class Heap
{
private:
/**
* A complete tree stored in a vector representing this
* binary heap
*/
vector<E> tree;
/**
* Swaps a parent and child elements of this heap at the specified     indices
* @param place an index of the child element on this heap
* @param parent an index of the parent element on this heap
*/
void swap(int place, int parent);
/**
* Rebuilds the heap to ensure that the heap property of the tree is preserved.
* @param root the root index of the subtree to be rebuilt
* @param eSize the size of this tree
*/
void reheapify(int root, int eSize);
public:
/**
Constructs an empty heap;
*/
Heap<E>();

/**
destructor - returns the heap memory to the system;
*/
~Heap<E>();

/**
Determine whether the heap is empty.
@return true if the heap is empty;
otherwise, it returns false if the tree contains at least one item.
*/
bool isEmpty() const;

/**
Inserts an item into the heap.
@param item the value to be inserted.
@return none
*/
void insert(E item);

/**
An exception is generated if this method is invoked
by an empty heap. The maximum/minimum value is removed
from the heap if the heap is not empty and its effective
size is reduced by 1.
@return the maximum (in the case of a maxheap) or the
minimum (in the case of a minheap) on the heap.
*/
E remove() throw (HeapException);

/**
An exception is generated if this method is invoked
by an empty heap
@return the maximum (in the case of a maxheap) or the
minimum (in the case of a minheap) on the heap.
*/
const E& peek() const throw (HeapException);/**
@return the size of the heap; the effective size of the
heap.
*/
int size() const;
};
//HEAP_H
#endif

Heap.cpp:

#include "Heap.h"
using namespace std;

template <typename E>
Heap<E>::Heap()
{
// compiler-generated code .. no need to implement this
}

template <typename E>
Heap<E>::~Heap()
{
while(tree.size() > 0)
tree.pop_back();
}

template <typename E>
bool Heap<E>::isEmpty() const
{
if (tree.empty())
return true;
else return false;
}

template<typename E>
void Heap<E>::insert(E item)
{
tree.push_back(item);
int place = tree.size() - 1;
int parent = place / 2;
if (place % 2 == 0)
parent = parent - 1;
while (parent >= 0 && tree[place] > tree[parent]){
swap(place,parent);
place = parent;
if (place % 2 == 0)
int parent = (place / 2) - 1;
else
parent = place / 2;
}
}

template<typename E>
E Heap<E>::remove() throw (HeapException)
{
if (isEmpty() == false){
int child = tree.size() - 1;
swap(child, 0);
E number = tree.back();
reheapify(0, tree.size());
return number;}
else {
throw ("Attempted to remove from empty Heap");
}}

template<typename E>
const E& Heap<E>::peek() const throw (HeapException)
{
if (isEmpty() == false)
return tree[0];
else throw ("Attempted to peek empty Heap");
}

template<typename E>
int Heap<E>::size()const
{
return tree.size;
}template<typename E>
void Heap<E>::swap(int place, int parent)
{
E temp;
temp = tree[place];
tree[place] = tree[parent];
tree[parent] = temp;

}

template<typename E>
void Heap<E>::reheapify(int root, int eSize)
{
int child = 2 * root + 1;
int right = 2 * root + 2;
if (child < eSize){
if (right < eSize && tree[right] < tree[child]){
child = child + 1;
}
if (tree[root] < tree[child]){
swap(root, child);
reheapify(child, eSize);
}
}
}

PCB.h:

#include <string>
#include <iostream>

using namespace std;class PCB
{
private:
/**
* the process ID
*/
int pid;
/**
* the priority value of this process [-20,19]
*/
int priority;
/**
* the running status of this process
* [0 = not running, 1 = running]
*/
int running;
/**
* the cycle during which this process was created
*/
int arrived;
/**
* the quantum (number of cycles required to execute)
* this process
*/
int length;
/**
* the cycle when this process began running
*/
int start;
/**
* the number of cycles from the creation of this process
* to when it began running
*/
int wait;
public:
/**
* Create a a PCB with the lowest priority
* and a quantum of 0 (default constructor)
*/
PCB()
{
priority = 19;
running = 0;
arrived = 0;
length = 0;
}

/**
* Creates a PCB with the specified parameters.
* @param id the process ID
* @param pVal priority value [-20,19]
* @param run executing status [0 = not running, 1 = running]
* @param arr the cycle during which the process arrived
* @param len the quantum - number of cycles required to execute
* the process
*/
PCB(int id, int pVal, int run, int arr, int len)
{
pid = id;
priority = pVal;
running = run;
arrived = arr;
length = len;
}

/**
* Gives the ID for this process.
* @return the pid of this process
*/
int getPid() const
{
return pid;
}

/**
* Gives the priority value for this process.
* @return the priority of this process
*/
int getPriority() const
{
return priority;
}

/**
* Gives the running status of this process.
* @return the running status of this process
*/
bool isExecuting() const
{
return (running == 1);
}

/**
* Sets the running status of this process to 1.
*/
void execute()
{
running = 1;
}

/**
* Gives the arrival time for this process.
* @return cycle during with this process was created
*/
int getArrival() const
{
return arrived;
}

/**
* Gives the quantum of this process.
* @return the number of cycles required to execute this process
*/
int getLength() const
{
return length;
}

/**
* Gives the cycle during which this process began running.
* @return the cycle during which this process began running
*/
int getStart() const
{
return start;
}

/**
* Sets the start cyle for this process.
* @param startCycle the cycle during which this process began
* running.
*/
void setStart(int startCycle)
{
start = startCycle;
}

/**
* Gives the wait time for this process.
* @return the number of cycles this process waited
* before running.
*/
int getWait() const
{
return wait;
}

/**
* Sets the wait time for this process.
*/
void setWait(int waitTime)
{
wait = waitTime;
}

/**
* Overloaded == operator that determines whether
* two process control blocks are the same.
* @param pcb1 a process control block
* @param pcb2 a process control block
* @return true if the PCBs are the same; otherwise, false
*/
friend bool operator==(const PCB& pcb1, const PCB& pcb2);
/**
* Overloaded != operator that determines whether
* two process control blocks are different.
* @param pcb1 a process control block
* @param pcb2 a process control block
* @return true if the PCBs are different; otherwise, false
*/
friend bool operator!=(const PCB& pcb1, const PCB& pcb2);
/**
* Overloaded > operator that determines whether
* the first PCB has a higher priority than the second.
* @param pcb1 a process control block
* @param pcb2 a process control block
* @return true if the first PCB has a higher priority than the second;
* otherwise, false
*/
friend bool operator>(const PCB& pcb1, const PCB& pcb2);
/**
* Overloaded < operator that determines whether
* the first PCB has a lower priority than the second.
* @param pcb1 a process control block
* @param pcb2 a process control block
* @return true if the first PCB has a lower priority than the second;
* otherwise, false
*/
friend bool operator<(const PCB& pcb1, const PCB& pcb2);
/**
* Overloaded >= operator that determines whether
* the first PCB has the same or higher priority than the second.
* @param pcb1 a process control block
* @param pcb2 a process control block
* @return true if the first PCB has the same or higher priority than
* the second; otherwise, false
*/
friend bool operator>=(const PCB& pcb1, const PCB& pcb2);
/**
* Overloaded <= operator that determines whether
* the first PCB has the same or lower priority than the second.
* @param pcb1 a process control block
* @param pcb2 a process control block
* @return true if the first PCB has the same or lower priority than
* the second; otherwise, false
*/
friend bool operator<=(const PCB& pcb1, const PCB& pcb2);
};

bool operator==(const PCB& pcb1, const PCB& pcb2)
{
return (pcb1.running == pcb2.running &&
pcb1.priority == pcb2.priority &&
pcb1.arrived == pcb2.arrived);
}

bool operator!=(const PCB& pcb1, const PCB& pcb2)
{
return (!(pcb1 == pcb2));
}

bool operator>(const PCB& pcb1, const PCB& pcb2)
{
if (pcb1.running > pcb2.running)
return true;
if (pcb1.running < pcb2.running)
return false;
if (pcb1.priority < pcb2.priority)
return true;
if (pcb1.priority > pcb2.priority)
return false;
if (pcb1.arrived < pcb2.arrived)
return true;
else
return false;
}

bool operator<(const PCB& pcb1, const PCB& pcb2)
{
return ((pcb1 != pcb2) && !(pcb1 > pcb2));
}

bool operator<=(const PCB& pcb1, const PCB& pcb2)
{
return (pcb1 > pcb2 || pcb1 == pcb2);
}

bool operator>=(const PCB& pcb1, const PCB& pcb2)
{
return (pcb1 > pcb2 || pcb1 == pcb2);
}

И мой главный до сих пор (мой вопрос появляется в операторе if, где я добавляю тип PCB в кучу. Просто хочу получить некоторое представление о том, где я должен взять это, потому что я потерян)

#include <cstdlib>
#include "Heap.cpp"#include "PCB.h"
using namespace std;

/*
*
*/
int main(int argc, char** argv) {

int j = 1;
Heap<PCB> a;
for (int i = 0; i < atoi(argv[2]); i++){
double q = ((double) rand() / (RAND_MAX));
double r = atof(argv[1]);

cout<<"*** Cycle #: "<<i+1<<endl;

if (q <= r){

PCB b(j,rand() % 39 + (-20), 0, i + 1, rand() % 100 + 1);
a.insert(b);
j++;
cout << "Adding job with pid #" <<b.getPid<<" and priority ";
cout << b.getPriority() << " and length "<< b.getLength();
cout << endl;
j++;
}
else
{ cout << "No new job this cycle" << endl;}

if ()
}return 0;
}

2

Решение

Задача ещё не решена.

Другие решения

Других решений пока нет …

По вопросам рекламы [email protected]