From 0f787e5a80161e90e177859207ffcfc59d57cefd Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 1 Nov 2026 11:46:55 +0000 Subject: [PATCH 1/4] Add cond_timed_wait primitive Wait on a condition variable 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 --- libs/std/thread.c | 50 ++++++++++++++++++++++++++++++++++++++ tests/CMakeLists.txt | 19 +++++++++++++++ tests/cond_timed_wait.neko | 33 +++++++++++++++++++++++++ 3 files changed, 102 insertions(+) create mode 100644 tests/cond_timed_wait.neko diff --git a/libs/std/thread.c b/libs/std/thread.c index 34f0b858..3c84445d 100644 --- a/libs/std/thread.c +++ b/libs/std/thread.c @@ -719,6 +719,42 @@ static void _cond_wait(vcondition *cond) { #endif } +// Upper bound for timed waits in seconds (about 31 years), so that deadlines +// and millisecond counts do not overflow. Non-positive and NaN timeouts become 0. +#define MAX_WAIT_SECONDS 1e9 + +static double _clamp_wait_timeout(double timeout) { + if (!(timeout > 0)) + return 0; + if (timeout > MAX_WAIT_SECONDS) + return MAX_WAIT_SECONDS; + return timeout; +} + +static bool _cond_timed_wait(vcondition *cond, double timeout) { +#ifdef NEKO_WINDOWS + double ms = _clamp_wait_timeout(timeout) * 1000.0; + // INFINITE (0xFFFFFFFF) would mean no timeout at all + DWORD dms = ms >= (double)(INFINITE - 1) ? INFINITE - 1 : (DWORD)ms; + if (SleepConditionVariableSRW(&cond->cond, &cond->lock, dms, 0)) + return true; + return GetLastError() != ERROR_TIMEOUT; +#else + struct timeval tv; + struct timespec t; + double delta = _clamp_wait_timeout(timeout); + long long sec = (long long)delta; + long long nsec = (long long)((delta - (double)sec) * 1e9); + gettimeofday(&tv, NULL); + nsec += (long long)tv.tv_usec * 1000; + sec += tv.tv_sec + nsec / 1000000000; + nsec %= 1000000000; + t.tv_sec = (time_t)sec; + t.tv_nsec = (long)nsec; + return pthread_cond_timedwait(&cond->cond, &cond->lock, &t) == 0; +#endif +} + static void _cond_signal(vcondition *cond) { #ifdef NEKO_WINDOWS WakeConditionVariable(&cond->cond); @@ -781,6 +817,19 @@ static value cond_wait(value *cond) { return val_null; } +/** + cond_timed_wait : 'condition -> timeout:number -> bool + + Waits on the condition variable for at most [timeout] seconds. + Returns false if the timeout expired, true otherwise. + +**/ +static value cond_timed_wait(value cond, value timeout) { + val_check_kind(cond, k_condition); + val_check(timeout, number); + return alloc_bool(_cond_timed_wait(val_cond(cond), val_number(timeout))); +} + static value cond_signal(value *cond) { val_check_kind(cond, k_condition); _cond_signal(val_cond(cond)); @@ -798,5 +847,6 @@ DEFINE_PRIM(cond_acquire, 1) DEFINE_PRIM(cond_try_acquire, 1) DEFINE_PRIM(cond_release, 1) DEFINE_PRIM(cond_wait, 1) +DEFINE_PRIM(cond_timed_wait, 2) DEFINE_PRIM(cond_signal, 1) DEFINE_PRIM(cond_broadcast, 1) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index ae988bc5..19c4c58e 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -14,3 +14,22 @@ set_tests_properties(run_goto.n PROPERTIES PASS_REGULAR_EXPRESSION "startcontinue1continue2end" FIXTURES_SETUP build_goto.n ) + +add_test(NAME build_cond_timed_wait.n + COMMAND nekoc -o ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/tests/ ${CMAKE_SOURCE_DIR}/tests/cond_timed_wait.neko + WORKING_DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} +) + +set_tests_properties(build_cond_timed_wait.n PROPERTIES + FIXTURES_SETUP cond_timed_wait +) + +add_test(NAME run_cond_timed_wait.n + COMMAND nekovm tests/cond_timed_wait.n + WORKING_DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} +) + +set_tests_properties(run_cond_timed_wait.n PROPERTIES + PASS_REGULAR_EXPRESSION "timeout:false,true;held:false;nonpositive:false,false,false,false;huge:true,false,true;" + FIXTURES_REQUIRED cond_timed_wait +) diff --git a/tests/cond_timed_wait.neko b/tests/cond_timed_wait.neko new file mode 100644 index 00000000..76b0b9c8 --- /dev/null +++ b/tests/cond_timed_wait.neko @@ -0,0 +1,33 @@ +// Tests std@cond_timed_wait: timing out, keeping the mutex, non-positive +// timeouts and huge timeouts that are signaled. +// Closures capture locals by value, so shared state lives in an array. +var create = $loader.loadprim("std@cond_create",0); +var acquire = $loader.loadprim("std@cond_acquire",1); +var try_acquire = $loader.loadprim("std@cond_try_acquire",1); +var release = $loader.loadprim("std@cond_release",1); +var timed_wait = $loader.loadprim("std@cond_timed_wait",2); +var signal = $loader.loadprim("std@cond_signal",1); +var thread_create = $loader.loadprim("std@thread_create",2); +var sleep = $loader.loadprim("std@sys_sleep",1); +var time = $loader.loadprim("std@sys_time",0); +var lock_create = $loader.loadprim("std@lock_create",0); +var lock_wait = $loader.loadprim("std@lock_wait",2); +var lock_release = $loader.loadprim("std@lock_release",1); + +var c = create(); +acquire(c); +var t = time(); +var r = timed_wait(c, 0.1); +$print("timeout:", r, ",", time() - t >= 0.09, ";"); +var l = lock_create(); +var st = $array(null, false); +thread_create(function(_) { st[0] = try_acquire(c); if( st[0] ) release(c); lock_release(l); }, null); +lock_wait(l, null); +$print("held:", st[0], ";"); +$print("nonpositive:", timed_wait(c, 0.0), ",", timed_wait(c, -1), ",", timed_wait(c, 0.0/0.0), ",", timed_wait(c, 0), ";"); +thread_create(function(_) { sleep(0.1); acquire(c); st[1] = true; signal(c); release(c); }, null); +var timedOut = false; +t = time(); +while( $not(st[1]) && $not(timedOut) ) if( $not(timed_wait(c, 1000000000000.0)) ) timedOut = true; +$print("huge:", st[1], ",", timedOut, ",", time() - t < 5, ";"); +release(c); From 9c587b96d34346a928d5b4100927c9bf5623816b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 2 Nov 2026 10:24:58 +0000 Subject: [PATCH 2/4] Report capped Windows timed waits as spurious wakeups SleepConditionVariableSRW takes a DWORD of milliseconds, so waits of more than about 49.7 days are capped. A capped wait that runs out had not reached the requested timeout, so return true like a spurious wakeup instead of false, which means that the timeout expired. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Va4FXDYWEo4mt53psuM5hu --- libs/std/thread.c | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/libs/std/thread.c b/libs/std/thread.c index 3c84445d..019cebfa 100644 --- a/libs/std/thread.c +++ b/libs/std/thread.c @@ -734,11 +734,15 @@ static double _clamp_wait_timeout(double timeout) { static bool _cond_timed_wait(vcondition *cond, double timeout) { #ifdef NEKO_WINDOWS double ms = _clamp_wait_timeout(timeout) * 1000.0; - // INFINITE (0xFFFFFFFF) would mean no timeout at all - DWORD dms = ms >= (double)(INFINITE - 1) ? INFINITE - 1 : (DWORD)ms; + // INFINITE (0xFFFFFFFF) would mean no timeout at all, so waits of more than + // about 49.7 days are cut short + bool capped = ms >= (double)(INFINITE - 1); + DWORD dms = capped ? INFINITE - 1 : (DWORD)ms; if (SleepConditionVariableSRW(&cond->cond, &cond->lock, dms, 0)) return true; - return GetLastError() != ERROR_TIMEOUT; + // a capped wait that runs out did not reach the requested timeout, so it + // counts as a spurious wakeup + return GetLastError() != ERROR_TIMEOUT || capped; #else struct timeval tv; struct timespec t; From e19fa8d8fd1da906ab631ba4a3a175daf5ae1482 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 14:48:00 +0000 Subject: [PATCH 3/4] Return false for all non-timeout errors on Windows too The Windows timed wait returned true for every error other than ERROR_TIMEOUT, while the POSIX path returns false for any error. Such errors are misuse that should not occur, and returning true would make a predicate loop spin on a persistent error, so return false like on POSIX. Only a capped wait that runs out still counts as a spurious wakeup. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Va4FXDYWEo4mt53psuM5hu --- libs/std/thread.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/libs/std/thread.c b/libs/std/thread.c index 019cebfa..9d99e4b3 100644 --- a/libs/std/thread.c +++ b/libs/std/thread.c @@ -741,8 +741,8 @@ static bool _cond_timed_wait(vcondition *cond, double timeout) { if (SleepConditionVariableSRW(&cond->cond, &cond->lock, dms, 0)) return true; // a capped wait that runs out did not reach the requested timeout, so it - // counts as a spurious wakeup - return GetLastError() != ERROR_TIMEOUT || capped; + // counts as a spurious wakeup. Other errors return false like on POSIX. + return capped && GetLastError() == ERROR_TIMEOUT; #else struct timeval tv; struct timespec t; From f8ee6738a551417ca07855d1ec1a49f8f75ebab0 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 10:25:43 +0000 Subject: [PATCH 4/4] Use a monotonic clock for cond_timed_wait, add a test timeout - gettimeofday follows changes to the system time, which could shorten or lengthen a timed wait. Create condition variables with CLOCK_MONOTONIC and compute the deadline with clock_gettime. macOS has no pthread_condattr_setclock, so use the relative pthread_cond_timedwait_relative_np there. - Give the cond_timed_wait ctest a timeout, so that a hanging wait fails the test instead of the whole run. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Va4FXDYWEo4mt53psuM5hu --- libs/std/thread.c | 28 ++++++++++++++++++++++++---- tests/CMakeLists.txt | 1 + 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/libs/std/thread.c b/libs/std/thread.c index 9d99e4b3..09638e27 100644 --- a/libs/std/thread.c +++ b/libs/std/thread.c @@ -33,6 +33,7 @@ #else # include # include +# include typedef struct _vlock { pthread_mutex_t lock; pthread_cond_t cond; @@ -683,7 +684,19 @@ static void _cond_init(vcondition *cond) { InitializeConditionVariable(&cond->cond); #else pthread_mutex_init(&cond->lock, NULL); +# ifdef NEKO_MAC + // macOS has no pthread_condattr_setclock; _cond_timed_wait uses a + // relative timeout there instead pthread_cond_init(&cond->cond, NULL); +# else + // measure timed waits on the monotonic clock, so that changes to the + // system time don't shorten or lengthen them + pthread_condattr_t attr; + pthread_condattr_init(&attr); + pthread_condattr_setclock(&attr, CLOCK_MONOTONIC); + pthread_cond_init(&cond->cond, &attr); + pthread_condattr_destroy(&attr); +# endif #endif } @@ -744,18 +757,25 @@ static bool _cond_timed_wait(vcondition *cond, double timeout) { // counts as a spurious wakeup. Other errors return false like on POSIX. return capped && GetLastError() == ERROR_TIMEOUT; #else - struct timeval tv; struct timespec t; double delta = _clamp_wait_timeout(timeout); long long sec = (long long)delta; long long nsec = (long long)((delta - (double)sec) * 1e9); - gettimeofday(&tv, NULL); - nsec += (long long)tv.tv_usec * 1000; - sec += tv.tv_sec + nsec / 1000000000; +# ifdef NEKO_MAC + t.tv_sec = (time_t)sec; + t.tv_nsec = (long)nsec; + return pthread_cond_timedwait_relative_np(&cond->cond, &cond->lock, &t) == 0; +# else + struct timespec now; + // the condition variable uses CLOCK_MONOTONIC, see _cond_init + clock_gettime(CLOCK_MONOTONIC, &now); + nsec += now.tv_nsec; + sec += now.tv_sec + nsec / 1000000000; nsec %= 1000000000; t.tv_sec = (time_t)sec; t.tv_nsec = (long)nsec; return pthread_cond_timedwait(&cond->cond, &cond->lock, &t) == 0; +# endif #endif } diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 19c4c58e..1b31c451 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -32,4 +32,5 @@ add_test(NAME run_cond_timed_wait.n set_tests_properties(run_cond_timed_wait.n PROPERTIES PASS_REGULAR_EXPRESSION "timeout:false,true;held:false;nonpositive:false,false,false,false;huge:true,false,true;" FIXTURES_REQUIRED cond_timed_wait + TIMEOUT 60 )