Repository navigation
Implement direct context switching between coroutines - #39
Conversation
This change optimizes coroutine scheduling by allowing tasks to directly switch to the next ready task instead of always returning to the scheduler. Key changes: - Simplified coroutine states (removed "running", kept ready/waiting/dead) - Enhanced yield() to take desired state and perform direct switching - Added next_ready_queue to track tasks yielding as ready - Removed deprecated waitForReady() methods across the codebase - Updated all I/O and synchronization operations to use new yield() API - Changed AwaitableList.append() to push() for consistency This reduces context switch overhead and improves runtime performance.
WalkthroughRefactors coroutine scheduling: removes waitForReady, introduces Runtime.yield(desired_state), adds next_ready_queue, and switches list enqueues from append to push. Updates coroutines, sync primitives, and I/O (file/tcp/udp) to yield .waiting and tests/examples to yield .ready. Removes CoroutineState.running and adds current coroutine helpers. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant C as Coroutine
participant R as Runtime
participant A as Awaitable (e.g., I/O or Mutex)
Note over C,R: Waiting flow (new)
C->>A: enqueue waiter (A.waiting_list.push)
C->>R: yield(.waiting)
activate R
R->>R: stage C in next_ready_queue (when woken)
deactivate R
A-->>R: markReady(C)
Note over R: Scheduling loop
R->>R: move next_ready_queue -> ready_queue
R->>C: run next ready coroutine
Note over C,R: Ready yield (cooperative)
C->>R: yield(.ready)
R->>R: push C to next_ready_queue
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 (7)
🔇 Additional comments (13)
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 |
Integrated the new Awaitable abstraction from main that supports both coroutine and thread waiting. Updated the direct switching implementation to work correctly with the new waitForComplete() and markComplete() APIs. Key changes: - Updated Awaitable.waitForComplete() to use runtime.yield(.waiting) instead of removed waitForReady() - Changed all append() calls to push() for consistency - Fixed dead coroutine handling to use correct awaitable reference - All tests passing
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (3)
src/tcp.zig (1)
96-96: Yield switchovers look correct; consider a fast-path for immediate completions.The replacements to
waiter.runtime.yield(.waiting)align with the new scheduler model and look good. If any xev ops can complete synchronously (invoke the callback before we reachyield), we’ll still yield once unnecessarily. Optional: add a “completed” flag inResultand skip yielding if already done.Example (apply similarly to accept/close/connect/write/read/shutdown):
- const Result = struct { + const Result = struct { waiter: Waiter, result: xev.ConnectError!void = undefined, + completed: bool = false, pub fn callback( result_data_ptr: ?*@This(), loop: *xev.Loop, completion_inner: *xev.Completion, socket: xev.TCP, result: xev.ConnectError!void, ) xev.CallbackAction { _ = loop; _ = completion_inner; _ = socket; const result_data = result_data_ptr.?; result_data.result = result; + result_data.completed = true; result_data.waiter.markReady(); return .disarm; } }; @@ - waiter.runtime.yield(.waiting); + if (!result_data.completed) { + waiter.runtime.yield(.waiting); + }Please confirm whether xev ever calls these TCP callbacks synchronously. If it does, the fast-path avoids an extra yield; if not, current code is fine.
Also applies to: 142-142, 201-201, 307-307, 346-346, 391-391, 440-440
src/sync.zig (2)
191-199: ResetEvent.wait: OK; clarify thread-affinity vs. “thread-safe” claim.The atomic state + queue push + yield is fine for a single-runtime-thread model. However, the doc says “ResetEvent is a thread-safe bool… Concurrent calls to set(), isSet(), reset() are allowed.”
set()iterateswait_queuew/o external locking; ifset()can be called from other OS threads, that would race withwait_queue.push/remove. Please clarify invariants (e.g., all methods must be invoked on the runtime thread) or add a runtime-thread assertion inset().
325-325: Tests: repeatedrt.yield(.ready)are fine; consider compacting.The explicit yields help sequencing with the new scheduler. Optional: replace repeated lines with a tiny loop or helper to reduce noise.
Also applies to: 397-400, 465-465, 523-526, 821-821, 855-856, 930-930, 967-967, 1175-1175
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (7)
examples/mutex_demo.zig(1 hunks)src/coroutines.zig(2 hunks)src/file.zig(7 hunks)src/runtime.zig(11 hunks)src/sync.zig(14 hunks)src/tcp.zig(7 hunks)src/udp.zig(3 hunks)
🔇 Additional comments (4)
src/sync.zig (4)
30-37: Mutex slow path: looks correct; confirmpushpreserves FIFO fairness.Replacing
appendwithpushand yielding.waitingis consistent. Please confirmAwaitableList.pushpreserves the previous FIFO behavior (append to tail) so lock handoff remains fair when paired withpop().
68-76: Condition.wait ordering: cooperative-safe; confirm no lost-wakeup edge.Enqueue (push) → unlock →
runtime.yield(.waiting)matches the new model and should avoid lost wake-ups under cooperative scheduling (no other task runs until we yield). Please confirmRuntime.yield(.waiting)cannot race against a priormarkReadyon the same coroutine in a way that leaves it stuck waiting.
82-83: Condition.timedWait push: OK.Using
pushbeforetimedWaitForReadyWithCallbackis consistent with the non-timed path and the removal-on-timeout callback. LGTM.
221-244: ResetEvent.timedWait push: OK.Push then
timedWaitForReadyWithCallbackwithremoveon timeout is correct and mirrors the Condition path. LGTM.
Replace manual UTF-8 to UTF-16 conversion with std.os.windows.sliceToPrefixedFileW for better path handling on Windows. This change: - Eliminates heap allocations for path conversion - Adds proper directory handle support for relative path operations - Enables automatic long path support via \\?\ prefix - Improves path normalization and edge case handling Modified functions in src/os/fs.zig: - openat(): Now properly handles directory-relative file opening - createat(): Now properly handles directory-relative file creation - renameat(): Now properly handles directory handles for both paths - unlinkat(): Now properly handles directory-relative file deletion All tests pass on Linux and Windows (via Wine).
Summary
This PR optimizes the coroutine scheduler by implementing direct context switching between tasks, reducing scheduler overhead and improving runtime performance.
runningstate from coroutines, now onlyready,waiting, anddeadyield(): Tasks can now directly switch to the next ready coroutine instead of always returning to the schedulernext_ready_queue: Tracks tasks that yield as ready for the next scheduling cyclewaitForReady()methods across the codebaseAwaitableList.append()topush()yield()APIImplementation Details
The key optimization is in
Runtime.yield()which now:ready,waiting, ordead)ready, adds tonext_ready_queuefor next cycleThis reduces the number of context switches through the scheduler's main context, improving performance for workloads with many cooperative yields.
Test plan
Summary by CodeRabbit
New Features
Refactor
Tests
Chores