From ad7d4eb07dbc3a11deee5a64151dda935edc7c6f Mon Sep 17 00:00:00 2001 From: Tamino Bauknecht Date: Mon, 23 Oct 2023 00:54:01 +0200 Subject: [PATCH] sleeper_thread: Allow sleep_for with max duration The standard library has the implicit requirement that for std::condition_variable::sleep_for() the duration must not cause an overflow if added to the current time. This commit will reduce the duration accordingly to fit into the duration type. --- include/util/sleeper_thread.hpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/include/util/sleeper_thread.hpp b/include/util/sleeper_thread.hpp index 80acf169..4eee0aec 100644 --- a/include/util/sleeper_thread.hpp +++ b/include/util/sleeper_thread.hpp @@ -67,6 +67,12 @@ class SleeperThread { auto sleep_for(std::chrono::system_clock::duration dur) { std::unique_lock lk(mutex_); CancellationGuard cancel_lock; + using timepoint = std::chrono::system_clock::time_point; + static_assert(std::numeric_limits::max() >= + std::numeric_limits::max()); + if (std::chrono::system_clock::now() >= timepoint::max() - dur) { + dur = timepoint::max() - std::chrono::system_clock::now() - std::chrono::seconds(1); + } return condvar_.wait_for(lk, dur, [this] { return signal_ || !do_run_; }); }