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.
pull/2601/head
Tamino Bauknecht 2023-10-23 00:54:01 +02:00
parent a459d8a9b3
commit ad7d4eb07d
No known key found for this signature in database
GPG Key ID: 77837396BE935C6C
1 changed files with 6 additions and 0 deletions

View File

@ -67,6 +67,12 @@ class SleeperThread {
auto sleep_for(std::chrono::system_clock::duration dur) { auto sleep_for(std::chrono::system_clock::duration dur) {
std::unique_lock lk(mutex_); std::unique_lock lk(mutex_);
CancellationGuard cancel_lock; CancellationGuard cancel_lock;
using timepoint = std::chrono::system_clock::time_point;
static_assert(std::numeric_limits<timepoint::rep>::max() >=
std::numeric_limits<decltype(dur)::rep>::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_; }); return condvar_.wait_for(lk, dur, [this] { return signal_ || !do_run_; });
} }