From c75ca1999e76da939faac9524d5b4552d579c2c5 Mon Sep 17 00:00:00 2001 From: Nathan Giddings Date: Sat, 1 Aug 2020 16:12:55 -0500 Subject: [PATCH] Wrote priority queue for processes --- src/process.hpp | 23 ++++++++++++++++ src/processqueue.cpp | 62 ++++++++++++++++++++++++++++++++++++++++++++ src/processqueue.hpp | 35 +++++++++++++++++++++++++ 3 files changed, 120 insertions(+) create mode 100644 src/process.hpp create mode 100644 src/processqueue.cpp create mode 100644 src/processqueue.hpp diff --git a/src/process.hpp b/src/process.hpp new file mode 100644 index 0000000..68d6133 --- /dev/null +++ b/src/process.hpp @@ -0,0 +1,23 @@ +#ifndef PROCESS_H +#define PROCESS_H + +#include + +namespace kernel +{ + +class Process +{ +public: + + Process(); + + size_t priority; + + void* stack; + +}; + +}; + +#endif \ No newline at end of file diff --git a/src/processqueue.cpp b/src/processqueue.cpp new file mode 100644 index 0000000..4a9b929 --- /dev/null +++ b/src/processqueue.cpp @@ -0,0 +1,62 @@ +#include "processqueue.hpp" + +kernel::ProcessQueue::ProcessQueue(Process** array) +{ + m_array = array; + m_size = 0; +} + +kernel::Process* kernel::ProcessQueue::extractMin() +{ + if(m_size == 0) + return NULL; + m_size--; + Process* p = m_array[0]; + m_array[0] = m_array[m_size]; + heapify(0); +} + +void kernel::ProcessQueue::insert(Process* n) +{ + size_t i = m_size; + m_size++; + for(; i > 0 && m_array[(i - 1) / 2]->priority > n->priority; i = (i - 1) / 2) + { + m_array[i] = m_array[(i - 1) / 2]; + } + m_array[i] = n; +} + +void kernel::ProcessQueue::remove(Process* n) +{ + for(size_t i = 0; i < m_size; i++) + { + if(m_array[i] == n) + { + m_size--; + m_array[i] = m_array[m_size]; + heapify(i); + break; + } + } +} + +void kernel::ProcessQueue::heapify(size_t i) +{ + if(i * 2 + 1 >= m_size) + return; + if (m_array[i]->priority >= m_array[i * 2 + 1]->priority && m_array[i * 2 + 1]->priority <= m_array[i * 2 + 2]->priority) + { + Process* buffer = m_array[i]; + m_array[i] = m_array[i * 2 + 1]; + m_array[i * 2 + 1] = buffer; + heapify(i * 2 + 1); + } + else if (m_array[i]->priority >= m_array[i * 2 + 2]->priority && m_array[i * 2 + 2]->priority <= m_array[i * 2 + 1]->priority) + { + Process* buffer = m_array[i]; + m_array[i] = m_array[i * 2 + 2]; + m_array[i * 2 + 2] = buffer; + heapify(i * 2 + 2); + } +} \ No newline at end of file diff --git a/src/processqueue.hpp b/src/processqueue.hpp new file mode 100644 index 0000000..64b3f91 --- /dev/null +++ b/src/processqueue.hpp @@ -0,0 +1,35 @@ +#ifndef HEAP_H +#define HEAP_H + +#include + +#include "process.hpp" + +namespace kernel +{ + +class ProcessQueue +{ +public: + + ProcessQueue(Process** array); + + Process* extractMin(); + + void insert(Process* n); + + void remove(Process* n); + +private: + + void heapify(size_t index); + + Process** m_array; + + size_t m_size; + +}; + +} + +#endif \ No newline at end of file