Skip to content

Add thread parking support for task.join() and future.wait() - #37

Merged
lalinsky merged 2 commits into
mainfrom
thread-parking-support
Oct 9, 2025
Merged

lalinsky merged 2 commits into
mainfrom
thread-parking-support

Conversation

@lalinsky

@lalinsky lalinsky commented Oct 8, 2025 •

Copy link
Copy Markdown
Owner

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:

  • Added state field to Awaitable: Tracks completion (0 = pending, 1 = complete)
  • Added waitForComplete() method: Detects if called from coroutine or thread
    • From coroutine: uses existing wait queue and suspension
    • From thread: uses futex-based parking
  • Added markComplete() method: Wakes all waiters
    • Wakes coroutines via markReady()
    • Wakes threads via std.Thread.Futex.wake()

Cross-platform Support

Works on all platforms supported by std.Thread.Futex:

  • Linux/Android (native futex syscalls)
  • Windows (RtlWaitOnAddress via ntdll)
  • macOS/iOS (__ulock_wait2/__ulock_wake)
  • FreeBSD/OpenBSD/DragonFly (OS-specific primitives)
  • Fallback (pthread-based implementation)

Testing

  • All existing tests pass
  • Added example demonstrating thread-based join in examples/thread_join_demo.zig

Performance

  • Fast path: atomic load check (no syscall if already complete)
  • Slow path: futex operations are extremely fast (few hundred nanoseconds)
  • No overhead for coroutine-only usage

Summary by CodeRabbit

  • New Features

    • Wait for task/future completion from regular threads and coroutines, with optional timeouts.
    • Join tasks across threads (cross-thread joinability).
  • Improvements

    • Unified completion signaling that reliably wakes all waiters across contexts.
  • Documentation

    • Added example demonstrating joining a task from the main thread while the runtime runs in a background thread.

@coderabbitai

coderabbitai Bot commented Oct 8, 2025 •

Copy link
Copy Markdown
Contributor

Note

Other AI code review bot(s) detected

CodeRabbit 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.

Walkthrough

Unifies 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

Cohort / File(s) Summary
Example: thread join demo
examples/thread_join_demo.zig
New example that starts a runtime on a background OS thread, spawns a worker task, sleeps briefly, then joins the task from the main (non-coroutine) thread; waits for runtime thread to finish; logs results.
Runtime: Awaitable API & cross-thread waits
src/runtime.zig
Adds Awaitable.state: std.atomic.Value(u32) and public methods waitForComplete, timedWaitForComplete, and markComplete. Implements coroutine enqueue/suspend and thread futex parking, timed wait support, and centralized completion signaling. Replaces per-waiter wake logic across task/future/blocking paths to use the new APIs.

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
Loading
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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

A rabbit taps the runtime’s beat,
Atomics hum beneath my feet.
Threads nap on futex beds so deep,
Coros wake from suspended sleep.
Join across the seam — one hop, complete. 🐇✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title clearly and concisely summarizes the primary enhancement of the changeset by stating that thread parking support is being added for task.join() and future.wait(), which aligns directly with the pull request’s main objective of enabling cross-thread joins via futex-based parking.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch thread-parking-support

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 85e5ad3 and c59b23d.

📒 Files selected for processing (1)
  • src/runtime.zig (7 hunks)

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.

@lalinsky
lalinsky force-pushed the thread-parking-support branch from a0881e3 to f419e15 Compare October 8, 2025 15:50
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.
@lalinsky
lalinsky force-pushed the thread-parking-support branch from f419e15 to 85e5ad3 Compare October 8, 2025 15:52

@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: 0

🧹 Nitpick comments (1)
examples/thread_join_demo.zig (1)

29-42: Consider using defer for 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 using defer immediately 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 waitForComplete itself) would be more robust.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 53c70e1 and 85e5ad3.

📒 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 for std.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), markComplete will wake the coroutine since it's already in the waiting_list.
  • Thread path (lines 164-169): The while-loop with futex.wait correctly handles spurious wakeups, and the .acquire memory ordering ensures visibility of the .release store in markComplete.

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 try at line 215 will propagate error.Timeout immediately 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:

  1. Sets state with .release ordering (line 223), ensuring all prior writes are visible to waiters.
  2. Wakes all waiting coroutines by iterating the waiting_list (lines 226-229).
  3. Wakes all waiting threads via futex broadcast (line 232).

The waiting_list operations 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() and markComplete() methods:

  • markComplete() is always invoked from the runtime loop context (lines 116, 367, 875), which is appropriate since it manipulates the waiting_list.
  • waitForComplete() is used in join() and wait() 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

@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

🧹 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 unnecessary

You 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 visibility

If 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

📥 Commits

Reviewing files that changed from the base of the PR and between 53c70e1 and 85e5ad3.

📒 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 good

Switching to awaitable.markComplete(self) centralizes wakeups and simplifies the drain path. No issues spotted.


366-368: Future completion path LGTM

markComplete centralizes wakeups for both coroutines and threads. Looks correct.


376-378: Unified wait for Future is fine

Fast-path get + awaitable wait is correct. No issues spotted.


460-462: BlockingTask join path LGTM

Unified waiting via awaitable works here too. No issues spotted.


874-876: Use markComplete on coroutine death — good

This 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) for Futex.wait.

Likely an incorrect or invalid review comment.

Comment thread src/runtime.zig
Comment on lines +172 to +219
/// 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);
}
}
}

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.

🛠️ 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);
  • timedWait returns error.Timeout on timeout and accepts nanoseconds as a u64.
🤖 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).

Comment thread src/runtime.zig Resolved
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]>
@lalinsky
lalinsky merged commit 0c5465d into main Oct 9, 2025
@lalinsky
lalinsky deleted the thread-parking-support branch October 23, 2025 21:01
lalinsky added a commit that referenced this pull request Jan 6, 2026
…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
@coderabbitai coderabbitai Bot mentioned this pull request Feb 3, 2026
4 tasks done
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