Skip to content

Commit 1924b4c

Browse files
committed
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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Va4FXDYWEo4mt53psuM5hu
1 parent c9892dc commit 1924b4c

2 files changed

Lines changed: 24 additions & 0 deletions

File tree

‎include/hx/thread/ConditionVariable.hpp‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ namespace hx
1818
bool tryAcquire();
1919
void release();
2020
void wait();
21+
bool timedWait(double seconds);
2122
void signal();
2223
void broadcast();
2324

‎src/hx/thread/ConditionVariable.cpp‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,29 @@ void hx::thread::ConditionVariable_obj::wait()
4444
impl->condition.wait(impl->mutex);
4545
}
4646

47+
bool hx::thread::ConditionVariable_obj::timedWait(double seconds)
48+
{
49+
// Upper bound for the timeout, about 31 years. Larger values would overflow
50+
// the integer nanosecond count of the clock once added to the current time.
51+
constexpr double maxSeconds = 1e9;
52+
53+
// `!(seconds > 0)` also catches NaN.
54+
if (!(seconds > 0))
55+
{
56+
seconds = 0;
57+
}
58+
else if (seconds > maxSeconds)
59+
{
60+
seconds = maxSeconds;
61+
}
62+
63+
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::duration<double>(seconds));
64+
65+
hx::AutoGCFreeZone zone;
66+
67+
return impl->condition.wait_for(impl->mutex, duration) == std::cv_status::no_timeout;
68+
}
69+
4770
void hx::thread::ConditionVariable_obj::signal()
4871
{
4972
impl->condition.notify_one();

0 commit comments

Comments
 (0)