From 1924b4ccebb030d5460046027f935c27759b8092 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 1 Nov 2026 11:40:51 +0000 Subject: [PATCH] Add timedWait to ConditionVariable Wait for at most the given number of seconds and return false if the timeout expired. Non-positive and NaN timeouts don't block, and very large ones are clamped so that the deadline does not overflow. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Va4FXDYWEo4mt53psuM5hu --- include/hx/thread/ConditionVariable.hpp | 1 + src/hx/thread/ConditionVariable.cpp | 23 +++++++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/include/hx/thread/ConditionVariable.hpp b/include/hx/thread/ConditionVariable.hpp index aef1f83e1..d78937803 100644 --- a/include/hx/thread/ConditionVariable.hpp +++ b/include/hx/thread/ConditionVariable.hpp @@ -18,6 +18,7 @@ namespace hx bool tryAcquire(); void release(); void wait(); + bool timedWait(double seconds); void signal(); void broadcast(); diff --git a/src/hx/thread/ConditionVariable.cpp b/src/hx/thread/ConditionVariable.cpp index 3bfe2c1a4..a42e48d84 100644 --- a/src/hx/thread/ConditionVariable.cpp +++ b/src/hx/thread/ConditionVariable.cpp @@ -44,6 +44,29 @@ void hx::thread::ConditionVariable_obj::wait() impl->condition.wait(impl->mutex); } +bool hx::thread::ConditionVariable_obj::timedWait(double seconds) +{ + // Upper bound for the timeout, about 31 years. Larger values would overflow + // the integer nanosecond count of the clock once added to the current time. + constexpr double maxSeconds = 1e9; + + // `!(seconds > 0)` also catches NaN. + if (!(seconds > 0)) + { + seconds = 0; + } + else if (seconds > maxSeconds) + { + seconds = maxSeconds; + } + + auto duration = std::chrono::duration_cast(std::chrono::duration(seconds)); + + hx::AutoGCFreeZone zone; + + return impl->condition.wait_for(impl->mutex, duration) == std::cv_status::no_timeout; +} + void hx::thread::ConditionVariable_obj::signal() { impl->condition.notify_one();