Commit c5f8e52707ef7b41308f2291216fbdcff3d11fc9

Authored by Wiebe Cazemier
1 parent b6284120

Use determinstic strict weak ordering for timed events

This should fix corruption. There were inexplicable stalls of timed
events, and the debugger showed the names were all corrupted. std::sort
can do that sort of thing, apparently.
Showing 2 changed files with 12 additions and 5 deletions
timer.cpp
... ... @@ -27,18 +27,18 @@ void CallbackEntry::updateExectedAt()
27 27 this->lastExecuted = std::chrono::steady_clock::now();
28 28 }
29 29  
30   -uint64_t CallbackEntry::getNextCallMs() const
  30 +void CallbackEntry::calculateNewWaitTime()
31 31 {
32 32 const std::chrono::milliseconds elapsedSinceLastCall = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - lastExecuted);
33 33 int64_t newDelay = this->interval - elapsedSinceLastCall.count();
34 34 if (newDelay < 0)
35 35 newDelay = 0;
36   - return newDelay;
  36 + this->timeTillNext = newDelay;
37 37 }
38 38  
39 39 bool CallbackEntry::operator <(const CallbackEntry &other) const
40 40 {
41   - return this->getNextCallMs() < other.getNextCallMs();
  41 + return this->timeTillNext < other.timeTillNext;
42 42 }
43 43  
44 44 Timer::Timer()
... ... @@ -93,8 +93,13 @@ void Timer::addCallback(std::function&lt;void ()&gt; f, uint64_t interval_ms, const st
93 93  
94 94 void Timer::sortAndSetSleeptimeTillNext()
95 95 {
  96 + for(CallbackEntry &c : callbacks)
  97 + {
  98 + c.calculateNewWaitTime();
  99 + }
  100 +
96 101 std::sort(callbacks.begin(), callbacks.end());
97   - this->sleeptime = callbacks.front().getNextCallMs();
  102 + this->sleeptime = callbacks.front().timeTillNext;
98 103 }
99 104  
100 105 void Timer::process()
... ... @@ -131,6 +136,7 @@ void Timer::process()
131 136 continue;
132 137 }
133 138  
  139 + logger->logf(LOG_DEBUG, "Calling timed event '%s'.", callbacks.front().name.c_str());
134 140 CallbackEntry &c = callbacks.front();
135 141 c.updateExectedAt();
136 142 c.f();
... ...
... ... @@ -30,12 +30,13 @@ License along with FlashMQ. If not, see &lt;https://www.gnu.org/licenses/&gt;.
30 30 struct CallbackEntry
31 31 {
32 32 std::chrono::time_point<std::chrono::steady_clock> lastExecuted = std::chrono::steady_clock::now();
  33 + int64_t timeTillNext = 1000;
33 34 uint64_t interval = 0;
34 35 std::function<void ()> f = nullptr;
35 36 std::string name;
36 37  
37 38 void updateExectedAt();
38   - uint64_t getNextCallMs() const;
  39 + void calculateNewWaitTime();
39 40 bool operator <(const CallbackEntry &other) const;
40 41 };
41 42  
... ...