Repository navigation
Add thread parking support for task.join() and future.wait() - #37
Conversation
|
Note Other AI code review bot(s) detectedCodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review. WalkthroughUnifies awaitable wake/wait semantics to support cross-thread and coroutine waiting with atomic state, futex parking, and timeouts; adds Awaitable APIs (waitForComplete, timedWaitForComplete, markComplete) and updates Task/Future/BlockingTask completion paths. Also adds a Zig example demonstrating joining a task from the main thread while the runtime runs on a background thread. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor Main as Main Thread
participant RT as Runtime Thread
participant AW as Awaitable
participant TK as Task
Note over Main,RT: Setup
Main->>RT: spawn runtime thread (run loop)
Main->>RT: spawn task TK (associated with runtime)
RT->>TK: schedule/execute task
rect rgb(235,245,255)
Note right of AW: Unified waiting (coroutines & threads)
Main->>AW: waitForComplete() / timedWaitForComplete()
alt Already complete
AW-->>Main: return
else Coroutine caller
AW->>RT: enqueue waiter (suspend)
else Thread caller
AW->>AW: futex wait (park)
end
end
TK->>AW: markComplete(runtime)
AW->>RT: wake waiting coroutines
AW->>Main: futex wake threads
Main-->>Main: join returns result
RT-->>Main: runtime thread exits
sequenceDiagram
autonumber
actor Th as Thread (non-coroutine)
participant AW as Awaitable
Th->>AW: timedWaitForComplete(timeout_ns)
alt Completes before timeout
AW-->>Th: return
else Timeout
AW-->>Th: error.Timeout
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
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. Comment |
a0881e3 to
f419e15
Compare
Enables task.join(), future.wait(), and blocking task joins to work from regular threads (not just coroutines) by using std.Thread.Futex for thread parking on Linux, Windows, macOS, and other platforms. Key changes: - Add state field to Awaitable for tracking completion - Add waitForComplete() method that works from both coroutines and threads - Add timedWaitForComplete() with timeout support for both execution contexts - Add markComplete() method that wakes both coroutines and threads - Update all task/future completion paths to use markComplete() - Update all join/wait methods to use waitForComplete() The implementation uses futex-based parking (via std.Thread.Futex) when called from threads, and the existing coroutine suspension mechanism when called from coroutines. This enables incremental migration to coroutines and allows main threads to join spawned tasks.
f419e15 to
85e5ad3
Compare
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
examples/thread_join_demo.zig (1)
29-42: Consider usingdeferfor thread cleanup.The explicit
runtime_thread.join()at line 42 works correctly, but for consistency with the other resource cleanup patterns in this function (allocator, runtime, task), consider usingdeferimmediately after spawning:const runtime_thread = try std.Thread.spawn(.{}, runRuntimeInThread, .{&runtime}); +defer runtime_thread.join(); // Wait for a moment to let the runtime start std.time.sleep(5 * std.time.ns_per_ms); std.log.info("Main thread: calling task.join() from main thread (NOT a coroutine)", .{}); // This is the key feature: join() works from a regular thread! const result = task.join(); std.log.info("Main thread: task.join() returned: {}", .{result}); - -// Wait for runtime thread to finish -runtime_thread.join();Note: The 5ms sleep at line 32 is a simple but fragile way to ensure the runtime starts before joining. This is acceptable for a demo, but in production code, a proper synchronization mechanism (like a condition variable or the new
waitForCompleteitself) would be more robust.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
examples/thread_join_demo.zig(1 hunks)src/runtime.zig(7 hunks)
🔇 Additional comments (5)
examples/thread_join_demo.zig (1)
11-13: LGTM!The wrapper function correctly propagates errors from
runtime.run()and serves as a clean adapter forstd.Thread.spawn.src/runtime.zig (4)
147-170: Well-designed synchronization for cross-context waiting!The implementation correctly handles both coroutine and thread contexts:
- Fast path (line 149): Early return if already complete avoids syscalls.
- Coroutine path (lines 151-163): The double-check pattern after adding to the wait queue correctly handles the race where completion occurs between the initial check and suspension. Even if the state becomes 1 after the double-check (line 157) but before
waitForReady()(line 163),markCompletewill wake the coroutine since it's already in thewaiting_list.- Thread path (lines 164-169): The while-loop with
futex.waitcorrectly handles spurious wakeups, and the.acquirememory ordering ensures visibility of the.releasestore inmarkComplete.
176-218: LGTM! Timeout handling is correct.The timeout implementation properly handles both contexts:
- Coroutine path: Integrates with the runtime's timer infrastructure and uses a callback to remove from wait queue on timeout.
- Thread path: The
tryat line 215 will propagateerror.Timeoutimmediately when the futex times out, correctly exiting the while loop. The loop only continues on successful returns where the state is still 0 (spurious wakeups).
221-233: LGTM! Proper memory ordering and wake semantics.The completion mechanism correctly:
- Sets state with
.releaseordering (line 223), ensuring all prior writes are visible to waiters.- Wakes all waiting coroutines by iterating the
waiting_list(lines 226-229).- Wakes all waiting threads via futex broadcast (line 232).
The
waiting_listoperations are safe because they only occur on the runtime loop thread, avoiding the need for explicit synchronization.
116-116: Excellent integration of the unified completion mechanism!All call sites correctly use the new
waitForComplete()andmarkComplete()methods:
markComplete()is always invoked from the runtime loop context (lines 116, 367, 875), which is appropriate since it manipulates thewaiting_list.waitForComplete()is used injoin()andwait()methods (lines 312, 377, 461), correctly supporting both coroutine and thread callers.The refactoring successfully replaces the previous per-type waiter logic with a universal completion primitive.
Also applies to: 312-312, 367-367, 377-377, 461-461, 875-875
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (3)
src/runtime.zig (1)
220-233: Memory ordering and wake-all OK; consider idempotence and doc note on lifetime
- store(1, .release) + acquire loads on waiters is correct.
- wake with maxInt(u32) is a reasonable wake-all.
Two follow-ups:
- markComplete may be called multiple times; implementation is effectively idempotent — good. Consider early-return if state already 1 to avoid extra list scans/wakes (micro).
- Thread waiters rely on the awaitable memory remaining valid until they return from wait. Document this contract (JoinHandle/Future must outlive waiters), or track thread waiters to defer destruction.
examples/thread_join_demo.zig (2)
31-37: Sleep before join likely unnecessaryYou can drop the startup sleep; join() will block via futex until completion regardless of when the runtime starts processing.
- // Wait for a moment to let the runtime start - std.time.sleep(5 * std.time.ns_per_ms); - std.log.info("Main thread: calling task.join() from main thread (NOT a coroutine)", .{}); // This is the key feature: join() works from a regular thread! const result = task.join();
28-30: Bubble up runtime thread errors for visibilityIf run() fails, the spawned thread’s error is currently dropped. Capture and propagate/log it.
- const runtime_thread = try std.Thread.spawn(.{}, runRuntimeInThread, .{&runtime}); + var thread_result: ?anyerror = null; + const runtime_thread = try std.Thread.spawn(.{}, struct { + fn entry(rt: *zio.Runtime, out: *?anyerror) void { + out.* = runRuntimeInThread(rt) catch |e| e; + } + }.entry, .{ &runtime, &thread_result }); @@ - runtime_thread.join(); + runtime_thread.join(); + if (thread_result) |e| return e;
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
examples/thread_join_demo.zig(1 hunks)src/runtime.zig(7 hunks)
🔇 Additional comments (6)
src/runtime.zig (6)
115-119: Unified completion path looks goodSwitching to awaitable.markComplete(self) centralizes wakeups and simplifies the drain path. No issues spotted.
366-368: Future completion path LGTMmarkComplete centralizes wakeups for both coroutines and threads. Looks correct.
376-378: Unified wait for Future is fineFast-path get + awaitable wait is correct. No issues spotted.
460-462: BlockingTask join path LGTMUnified waiting via awaitable works here too. No issues spotted.
874-876: Use markComplete on coroutine death — goodThis ensures all waiters (coroutines + threads) are awakened consistently. Looks correct.
140-170: Ignore the futex pointer change suggestion — &self.state already matches the required*const std.atomic.Atomic(u32)forFutex.wait.Likely an incorrect or invalid review comment.
| /// Wait for this awaitable to complete with a timeout. Works from both coroutines and threads. | ||
| /// Returns error.Timeout if the timeout expires before completion. | ||
| /// For coroutines, uses runtime timer infrastructure. | ||
| /// For threads, uses futex timedWait directly. | ||
| pub fn timedWaitForComplete(self: *Awaitable, timeout_ns: u64) error{Timeout}!void { | ||
| // Fast path: already complete? | ||
| if (self.state.load(.acquire) == 1) return; | ||
|
|
||
| if (coroutines.getCurrent()) |current| { | ||
| // Coroutine path: get runtime and use timer infrastructure | ||
| const task = AnyTask.fromCoroutine(current); | ||
| const rt = Runtime.fromCoroutine(current); | ||
|
|
||
| self.waiting_list.append(&task.awaitable); | ||
|
|
||
| if (self.state.load(.acquire) == 1) { | ||
| _ = self.waiting_list.remove(&task.awaitable); | ||
| return; | ||
| } | ||
|
|
||
| const TimeoutContext = struct { | ||
| wait_queue: *AwaitableList, | ||
| awaitable: *Awaitable, | ||
| }; | ||
|
|
||
| var timeout_ctx = TimeoutContext{ | ||
| .wait_queue = &self.waiting_list, | ||
| .awaitable = &task.awaitable, | ||
| }; | ||
|
|
||
| try rt.timedWaitForReadyWithCallback( | ||
| timeout_ns, | ||
| TimeoutContext, | ||
| &timeout_ctx, | ||
| struct { | ||
| fn onTimeout(ctx: *TimeoutContext) bool { | ||
| return ctx.wait_queue.remove(ctx.awaitable); | ||
| } | ||
| }.onTimeout, | ||
| ); | ||
| } else { | ||
| // Thread path: use futex timedWait | ||
| while (self.state.load(.acquire) == 0) { | ||
| try std.Thread.Futex.timedWait(&self.state, 0, timeout_ns); | ||
| } | ||
| } | ||
| } | ||
|
|
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major
🧩 Analysis chain
Timed futex wait pointer and error semantics
Same pointer concern applies here; timedWait should target the underlying u32.
Proposed change:
- try std.Thread.Futex.timedWait(&self.state, 0, timeout_ns);
+ try std.Thread.Futex.timedWait(&self.state.value, 0, timeout_ns)Please also confirm timedWait returns error.Timeout on timeout in your Zig version (the loop logic assumes that).
🌐 Web query:
In Zig std.Thread.Futex.timedWait, what errors are returned on timeout and what are the parameter units?
💡 Result:
- Timeout error: timedWait returns error.Timeout when the wait times out. [1]
- Parameter units: the timeout parameter is named timeout_ns and is a u64 count of nanoseconds (0 treated as "no time to wait" and returns Timeout if the value still equals expect). [1][2]
Timed futex wait pointer and error semantics
- In the thread path, pass the underlying
u32:
- try std.Thread.Futex.timedWait(&self.state, 0, timeout_ns);
+ try std.Thread.Futex.timedWait(&self.state.value, 0, timeout_ns);timedWaitreturnserror.Timeouton timeout and accepts nanoseconds as au64.
🤖 Prompt for AI Agents
In src/runtime.zig around lines 172 to 219, the thread-path call to
std.Thread.Futex.timedWait is passing the atomic wrapper instead of the
underlying u32 and needs to surface the futex timeout error correctly: change
the call to pass a pointer to the atomic's raw u32 storage (use the
AtomicU32/raw pointer accessor or a cast to *u32 as appropriate in this
codebase) as the first argument, keep the expected value (0) and timeout_ns
(u64) as-is, and let the function's error.Timeout propagate (i.e., continue
using try so Timeout bubbles up).
This change mirrors the self-join protection already present in Runtime.wait(). When a task attempts to join itself from within a coroutine, it will now panic with a clear error message instead of deadlocking. Co-authored-by: Lukáš Lalinský <[email protected]>
…keups (#37) * Refactor wake API to distinguish thread-safe and async-signal-safe wakeups This change splits the wake functionality into two methods: - wake() for efficient thread-safe wakeups - wakeFromAnywhere() for async-signal-safe wakeups (e.g., from signal handlers) Backend implementations: - io_uring, epoll, poll: Both methods use the same mechanism (eventfd/pipe are already async-signal-safe) - kqueue: wake() uses EVFILT_USER (efficient, no FDs), wakeFromAnywhere() uses eventfd (FreeBSD/NetBSD) or pipe (macOS) This prepares for future io_uring IORING_OP_MSG migration where separate mechanisms will be needed. * Add test for wakeFromAnywhere API
Summary
Enables
task.join(),future.wait(), and blocking task joins to work from regular threads, not just coroutines. This allows main threads to join spawned tasks and enables incremental migration to coroutines.Implementation
Added thread parking support using
std.Thread.Futex:statefield toAwaitable: Tracks completion (0 = pending, 1 = complete)waitForComplete()method: Detects if called from coroutine or threadmarkComplete()method: Wakes all waitersmarkReady()std.Thread.Futex.wake()Cross-platform Support
Works on all platforms supported by
std.Thread.Futex:Testing
examples/thread_join_demo.zigPerformance
Summary by CodeRabbit
New Features
Improvements
Documentation