From 352bc02de84996999e6d400a2adc86346c6a87ed Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Niccol=C3=B2=20Betto?= <niccolo.betto@skywarder.eu>
Date: Wed, 28 Dec 2022 16:28:24 +0100
Subject: [PATCH] [TaskScheduler] Use `std::greater` instead of inverting
 event's `operator<`

---
 src/shared/scheduler/TaskScheduler.cpp |  2 +-
 src/shared/scheduler/TaskScheduler.h   | 21 +++++++++++++++------
 2 files changed, 16 insertions(+), 7 deletions(-)

diff --git a/src/shared/scheduler/TaskScheduler.cpp b/src/shared/scheduler/TaskScheduler.cpp
index 824f3d8aa..fd522b481 100644
--- a/src/shared/scheduler/TaskScheduler.cpp
+++ b/src/shared/scheduler/TaskScheduler.cpp
@@ -152,7 +152,7 @@ void TaskScheduler::normalizeTasks()
 {
     int64_t currentTick = getTick();
 
-    std::priority_queue<Event> newAgenda;
+    EventQueue newAgenda;
     while (agenda.size() > 0)
     {
         Event event = agenda.top();
diff --git a/src/shared/scheduler/TaskScheduler.h b/src/shared/scheduler/TaskScheduler.h
index dacad42fb..97d4ef87e 100644
--- a/src/shared/scheduler/TaskScheduler.h
+++ b/src/shared/scheduler/TaskScheduler.h
@@ -59,7 +59,7 @@ namespace Boardcore
 class TaskScheduler : public ActiveObject
 {
 public:
-    typedef std::function<void()> function_t;
+    using function_t = std::function<void()>;
 
     /**
      * @brief It defines the tasks array maximum size
@@ -165,14 +165,23 @@ private:
         {
         }
 
-        bool operator<(const Event& e) const
+        /**
+         * @brief Compare two events based on the next tick.
+         * @note This is used to have the event with the lowest tick first in
+         * the agenda. Newly pushed events are moved up in the queue (see
+         * heap bubble-up) until the other tick is lower.
+         */
+        bool operator>(const Event& other) const
         {
-            // Note: operator < is reversed, so that the priority_queue will
-            // return the lowest element first
-            return this->nextTick > e.nextTick;
+            return this->nextTick > other.nextTick;
         }
     };
 
+    // Use `std::greater` as the comparator to have elements with the lowest
+    // tick first. Requires operator `>` to be defined for Event.
+    using EventQueue =
+        std::priority_queue<Event, std::vector<Event>, std::greater<Event>>;
+
     void run() override;
 
     /**
@@ -227,7 +236,7 @@ private:
     miosix::FastMutex mutex;  ///< Mutex to protect tasks and agenda.
     std::array<Task, TASKS_SIZE>* tasks;  ///< Holds all tasks to be scheduled.
     miosix::ConditionVariable condvar;    ///< Used when agenda is empty.
-    std::priority_queue<Event> agenda;    ///< Ordered list of functions.
+    EventQueue agenda;                    ///< Ordered list of functions.
 
     PrintLogger logger = Logging::getLogger("taskscheduler");
 };
-- 
GitLab