Skip to content

Support sync primitives in non-async contexts - #271

Merged
lalinsky merged 2 commits into
mainfrom
feature/sync-primitives-non-async
Feb 3, 2026
Merged

lalinsky merged 2 commits into
mainfrom
feature/sync-primitives-non-async

Conversation

@lalinsky

@lalinsky lalinsky commented Feb 3, 2026

Copy link
Copy Markdown
Owner

Summary

  • Refactor Waiter to support both async task and blocking thread contexts
  • When no task is present, uses std.Thread.Futex for blocking operations
  • Enables synchronization primitives to work from regular OS threads

Changes

  • Change Waiter.task from *AnyTask to ?*AnyTask
  • Split wait() and timedWait() into separate task and futex implementations
  • Update Runtime.sleep() to use Waiter.timedWait() instead of timer-based I/O
  • Update Runtime.yield() to call std.Thread.yield() when not in executor context
  • Add getCurrentTaskOrNull() and getCurrentExecutorOrNull() helper methods
  • Add cross-thread signaling tests for ResetEvent

Test plan

  • Added test for futex-based timed wait with timeout
  • Added test for foreign thread signaling async task
  • Added test for async task signaling foreign thread
  • Existing tests pass

Refactor Waiter to support both async task and blocking thread contexts.
When no task is present, uses std.Thread.Futex for blocking operations.

- Change Waiter.task from *AnyTask to ?*AnyTask
- Split wait/timedWait into separate task and futex implementations
- Update Runtime.sleep() to use Waiter instead of timer-based I/O
- Add getCurrentTaskOrNull() and getCurrentExecutorOrNull() helpers
- Add tests for cross-thread signaling with ResetEvent
@coderabbitai

coderabbitai Bot commented Feb 3, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This change makes Waiter dual-mode (task or futex) by making its task optional and adding futex-based wait/signal paths; runtime gains getCurrentTaskOrNull() / getCurrentExecutorOrNull() and adapts yield/sleep to no-executor threads; I/O wait uses task when present. Tests exercise cross-thread signaling. Time helpers added for timeout computations.

Changes

Cohort / File(s) Summary
Waiter dual-mode implementation
src/common.zig
Waiter.task changed to ?*AnyTask. Init uses getCurrentTaskOrNull(). Added futex-based and task-based wait/signal flows: waitFutex, timedWaitFutex, waitTask, timedWaitTask, and public wait, timedWait, signal that dispatch based on presence of a task. I/O wait paths updated to require/use task when available.
Runtime accessors and thread behavior
src/runtime.zig
Added pub fn getCurrentTaskOrNull() and pub fn getCurrentExecutorOrNull(). yield() now yields the OS thread when no executor is present. sleep() replaced direct EV-timer usage with Waiter-based timed wait.
Cross-thread synchronization tests
src/sync/ResetEvent.zig
Added two tests verifying signaling between native threads and async tasks (thread→task and task→thread) to validate futex/Waiter cross-thread semantics and memory ordering.
Time utilities
src/time.zig
Added Timestamp.now(clock) and Timeout.durationFromNow() to compute durations from timeouts (none → max, duration → value, deadline → deadline − now).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related PRs

Poem

A waiter wakes in two-fold ways,
Task-bound yields or futex stays,
Timers ticking, threads align,
Signal, wake, and mark the time. ⏱️

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Support sync primitives in non-async contexts' directly matches the main change: enabling synchronization primitives to work in both async task and blocking thread contexts.
Description check ✅ Passed The description clearly relates to the changeset, covering the Waiter refactoring, futex-based blocking, Runtime helper methods, and test additions that are all present in the code changes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/sync-primitives-non-async

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In `@src/common.zig`:
- Around line 116-159: timedWaitFutex returns error.Timeout on timeout but
timedWaitTask never does, causing inconsistent semantics; make timedWaitTask
mirror timedWaitFutex by detecting when the ev.Timer fires and returning
error.Timeout. Specifically, after creating var timer: ev.Timer = .init(timeout)
(the local named timer) and installing callback, have the callback set a small
flag/state on the Waiter (or call a helper on Waiter) to mark "timed_out", then
after the call to self.waitTask(...) check that flag (or query timer state) and
if it indicates the timer fired return error.Timeout; keep the existing defer
that clears the timer to avoid races. Update timedWait (and any callers
expecting error.Timeout) accordingly so both futex and task paths return
error.Timeout on timeout.

In `@src/time.zig`:
- Around line 429-434: durationFromNow() computes time until a Timeout.deadline
using Timestamp.now(.monotonic), which is incorrect if callers construct
Timeout.deadline from a realtime Timestamp; update the code and/or API contract:
either document that Timeout.deadline must be a monotonic timestamp (add a
comment on the Timeout type and on durationFromNow stating “deadline is
monotonic-only”), or provide a clock-aware variant (e.g.,
durationFromClock(nowClock: Clock) or durationFromRealtimeNow that accepts a
realtime Timestamp or Clock) and keep durationFromNow delegating to the
monotonic variant; reference Timeout.deadline, durationFromNow, and the use of
Timestamp.now(.monotonic) when making the change.

Comment thread src/common.zig Resolved
Comment thread src/time.zig
Comment on lines +429 to +434
pub fn durationFromNow(self: Timeout) Duration {
return switch (self) {
.none => .max,
.duration => |d| d,
.deadline => |ts| Timestamp.now(.monotonic).durationTo(ts),
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Clarify clock expectations for Timeout.deadline.
durationFromNow() always uses a monotonic “now.” If callers construct a .deadline from a realtime Timestamp, the computed duration will be wrong. Consider documenting “deadline is monotonic-only” or providing a clock-aware variant.

🤖 Prompt for AI Agents
In `@src/time.zig` around lines 429 - 434, durationFromNow() computes time until a
Timeout.deadline using Timestamp.now(.monotonic), which is incorrect if callers
construct Timeout.deadline from a realtime Timestamp; update the code and/or API
contract: either document that Timeout.deadline must be a monotonic timestamp
(add a comment on the Timeout type and on durationFromNow stating “deadline is
monotonic-only”), or provide a clock-aware variant (e.g.,
durationFromClock(nowClock: Clock) or durationFromRealtimeNow that accepts a
realtime Timestamp or Clock) and keep durationFromNow delegating to the
monotonic variant; reference Timeout.deadline, durationFromNow, and the use of
Timestamp.now(.monotonic) when making the change.

Waiter.timedWait should return the same error set as wait() - only
cancellation errors when cancel_mode allows. The caller determines if
timeout won by checking their condition (e.g., still in wait queue).

- Change timedWaitFutex to return void (not Timeoutable!void)
- Change timedWait return type to be conditional on cancel_mode
- Simplify Runtime.sleep() to directly call timedWait
- Update test to not expect error.Timeout
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant