Skip to content

Commit

Permalink
Fix stepEventLoop timeout handling
Browse files Browse the repository at this point in the history
- Respect user-provided timeout when timers exist
- Exit loop when epoll_wait times out with no events/timers

Fixes morganstanley#436
  • Loading branch information
staging-devin-ai-integration[bot] committed Dec 7, 2024
1 parent 765bd10 commit c7acf52
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions lib/hobbes/events/events.C
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

#include <hobbes/hobbes.H>
#include <hobbes/events/events.H>
#include <hobbes/util/perf.H>
Expand Down Expand Up @@ -92,17 +91,21 @@ void registerInterruptHandler(const std::function<void()>& fn) {
}

bool stepEventLoop(int timeoutMS, const std::function<bool()>& stopFn) {
bool status = true;
while (!stopFn()) {
if (!timers.empty()) {
auto next = timers.top().callTime;
auto timeUntilNext = next - std::chrono::high_resolution_clock::now();
int millis = std::chrono::duration_cast<std::chrono::milliseconds>(timeUntilNext).count();
timeoutMS = std::max(1, millis);
if (timeoutMS == -1) {
timeoutMS = std::max(1, millis);
} else {
timeoutMS = std::min(timeoutMS, std::max(1, millis));
}
}

struct epoll_event evts[64];
int fds = epoll_wait(threadEPollFD(), evts, sizeof(evts)/sizeof(evts[0]), timeoutMS);
bool status = true;
if (fds > 0) {
for (int fd = 0; fd < fds; ++fd) {
auto* c = reinterpret_cast<eventcbclosure*>(evts[fd].data.ptr);
Expand All @@ -112,6 +115,7 @@ bool stepEventLoop(int timeoutMS, const std::function<bool()>& stopFn) {
} else if (fds < 0) {
if (errno != EINTR) {
status = false;
break;
} else if (epClosures != nullptr) {
auto f = epClosures->find(-1);
if (f != epClosures->end()) {
Expand Down Expand Up @@ -142,10 +146,12 @@ bool stepEventLoop(int timeoutMS, const std::function<bool()>& stopFn) {
for (auto& timer : newTimers) {
timers.push(timer);
}
} else {
// No events and no timers, break on timeout
break;
}
return status;
}
return false;
return status;
}

void runEventLoop(const std::function<bool()>& stopFn) {
Expand Down

0 comments on commit c7acf52

Please sign in to comment.