Skip to content

Move task registry to global Runtime storage with sentinel-based shutdown - #59

Merged
lalinsky merged 7 commits into
mainfrom
global-task-registry
Oct 20, 2025
Merged

lalinsky merged 7 commits into
mainfrom
global-task-registry

Conversation

@lalinsky

@lalinsky lalinsky commented Oct 20, 2025 •

Copy link
Copy Markdown
Owner

Summary

This PR refactors the task registry from per-Executor local storage to a single global registry in Runtime, using ConcurrentQueue sentinel states to encode the closed state. This simplifies shutdown coordination and eliminates the need for separate accepting_spawns and global_task_count atomic fields.

Key Changes

  • Created AnyTaskList wrapper type with methods: add(), remove(), close(), isEmpty(), isClosed(), pop()
  • Removed Runtime.global_task_count and Runtime.accepting_spawns atomics
  • Moved task registry from Executor.tasks to Runtime.tasks
  • Sentinel state encoding:
    • sentinel0 (0b00) = empty/open
    • sentinel1 (0b01) = empty/closed
    • pointer = has tasks/open
  • Shutdown coordination: Atomic transition to sentinel1 ensures only one executor successfully triggers shutdown, making it safe for all executors to call maybeShutdown()
  • Added startup shutdown check in Executor.run() to handle the case where runtime starts with no tasks
  • Extracted shutdown logic into reusable maybeShutdown() helper function
  • Removed two problematic tests that unsafely manipulated the task registry

Benefits

  • Simpler shutdown logic using sentinel states instead of multiple atomics
  • Lock-free coordination between executors during shutdown
  • Fewer atomic operations during normal operation
  • Clearer separation of concerns (Runtime owns global state, Executors are workers)

Test plan

  • All 99 unit tests pass
  • Thread pool smoke test passes (previously hung, now fixed)
  • Multi-threaded executor tests pass
  • Format check passes

Summary by CodeRabbit

Release Notes

  • Refactor
    • Streamlined internal queue implementation for improved performance and reduced memory overhead.
    • Enhanced coroutine state management with atomic operations for more reliable task transitions.
    • Improved runtime task lifecycle management for better stability and shutdown handling.
    • Updated synchronization primitives with refined wait-queue behavior and state transition logic.

- Set num_executors to null for auto-detection
- Will use CPU count instead of single-threaded mode
- Better utilization of available hardware
This commit fixes critical race conditions that occurred in the multi-threaded
async runtime when tasks could be woken by another thread before they actually
yielded, leading to deadlocks.

## Race Conditions Fixed

1. **Wake-before-yield race**: Tasks could be resumed (state set to .ready) after
   preparing to wait but before the yield() call. The unconditional state.store()
   in yield() would then overwrite .ready with .waiting, leaving the task stuck.

2. **Invalid mutex state transitions**: Mutex.lock() could transition directly from
   unlocked -> has_waiters, skipping the locked_once state. This occurred when
   unlock() happened between tryTransition() check and push() to wait queue.

3. **Invalid ResetEvent state transitions**: Similar issue where ResetEvent could
   transition from is_set -> has_waiters, skipping the unset state.

4. **popOrTransition sentinel state**: When popping the last waiter, popOrTransition()
   would transition to hardcoded sentinel0 instead of the specified to_sentinel.

## Solution

### 1. Added .preparing_to_wait state (src/coroutines.zig)
- New intermediate state between .ready and .waiting
- Allows detection of early wakeup via atomic CAS

### 2. Atomic CAS in yield() (src/runtime.zig)
- Modified yield() to take expected_state and desired_state parameters
- Performs atomic CAS: if state is not expected_state, check if .ready (early wakeup)
- If woken early (.ready), skip suspend; if unexpected state, panic
- Updated all yield() callers to pass expected states

### 3. New ConcurrentQueue operations (src/utils/concurrent_queue.zig)
- pushOrTransition(from, to, item): Push item OR transition from->to atomically
  * Used by Mutex to prevent unlocked->has_waiters invalid transition
- pushUnless(forbidden, item): Push item unless in forbidden state
  * Used by ResetEvent to prevent is_set->has_waiters invalid transition
- Fixed popOrTransition() to use to_sentinel when emptying queue

### 4. Updated sync primitives
- Mutex.lock(): Use pushOrTransition() for atomic lock acquisition (src/sync/Mutex.zig)
- ResetEvent.wait/timedWait(): Use pushUnless() to avoid invalid transitions (src/sync/ResetEvent.zig)
- Condition.wait/timedWait(): Updated to use atomic yield pattern (src/sync/Condition.zig)
- All primitives now use .ready -> .preparing_to_wait -> .waiting flow

## Testing

All 105 tests pass. The ping-pong benchmark that previously deadlocked now runs
successfully without any race conditions.
Add a spin loop that runs the event loop in non-blocking mode before
blocking when the ready queue is empty. This significantly reduces
latency for high-frequency cross-thread task scheduling.

## Problem

When an executor's ready queue is empty, it blocks in `loop.run(.once)`
waiting for I/O. If another thread schedules a task remotely and calls
notify(), the sleeping executor must go through kernel wakeup, which
adds 5-20 microseconds of latency per wakeup.

For workloads like ping-pong with frequent cross-thread messaging, this
kernel wakeup latency dominated performance, causing 30x+ slowdown
compared to single-threaded execution.

## Solution

Before blocking, spin up to 100 iterations running `loop.run(.no_wait)`:
- Checks for I/O completions (non-blocking poll)
- Processes async wakeup events if fired
- Checks remote ready queue after each iteration
- Only blocks if still no work after spinning

This catches remote tasks within microseconds instead of waiting for
kernel wakeup, while still allowing I/O to progress during the spin.

## Results

Multi-threaded ping-pong benchmark (1M round trips):
- Before: 9858ms (101K rounds/sec)
- After: 4385ms (228K rounds/sec)
- Improvement: 2.25x faster

The spin loop eliminated most kernel wakeup latency, more than doubling
throughput for high-frequency cross-thread workloads.
Replace std.Thread.Mutex with atomic spinlock using mutation bit (0b10)
in the head pointer. This reduces the queue size from 24 bytes to 16 bytes
while maintaining all race condition protections.

Changes:
- Remove mutex field, use mutation bit spinlock pattern instead
- Restore acquireMutationLock/releaseMutationLock methods
- Update all operations (push, pop, remove, etc.) to use spinlock
- Remove CompactConcurrentQueue variant (no longer needed)
- Keep all race condition fixes (pushUnless, pushOrTransition, popOrTransition)

The lock-free design uses fetchOr/fetchAnd atomic operations with proper
memory ordering (.acquire/.release) to protect the non-atomic tail pointer
and doubly-linked list updates.

All 101 tests pass, including concurrent stress tests.
Clear item pointers while holding the mutation lock instead of after
releasing it. This prevents concurrent remove() calls from racing on
the same item's prev/next pointers, and ensures double-remove attempts
properly fail the early exit checks.
Extract common push logic into pushInternal() helper function.
This eliminates ~70 lines of duplicated code across push(),
pushUnless(), and pushOrTransition().
…down

Replace per-Executor task queues with a single global task registry in Runtime.
Remove accepting_spawns and global_task_count atomics in favor of sentinel
state encoding for closed state. Create AnyTaskList wrapper with add(), remove(),
close(), isEmpty(), isClosed(), and pop() methods.

Key changes:
- Sentinel states: sentinel0 (empty/open), sentinel1 (empty/closed)
- Atomic transition to closed state ensures only one executor triggers shutdown
- All executors can safely call maybeShutdown() via atomic CAS
- Shutdown check added at start of Executor.run() to handle empty task list
- Simplified shutdown logic with extracted maybeShutdown() helper
@coderabbitai

coderabbitai Bot commented Oct 20, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

This PR consolidates task lifecycle management through a new AnyTaskList registry, removes CompactConcurrentQueue entirely, updates the coroutine state machine with a preparing_to_wait state, and introduces atomic state transitions and new queue APIs (pushUnless, pushOrTransition) to eliminate lost wakeup races in synchronization primitives.

Changes

Cohort / File(s) Summary
Benchmark cleanup
benchmarks/concurrent_queue_bench.zig, benchmarks/echo_server.zig, benchmarks/ping_pong.zig
Removed all CompactConcurrentQueue references and related benchmark functions; simplified concurrency configuration to use std.Thread.getCpuCount() and updated Runtime initialization with .num_executors = null.
Coroutine state machine
src/coroutines.zig
Added preparing_to_wait = 1 to CoroutineState enum, shifted waiting to 2 and dead to 3; changed Coroutine.state from plain CoroutineState to std.atomic.Value(CoroutineState) with atomic store operations on state transitions.
Runtime task registry and scheduling
src/runtime.zig
Introduced public AnyTaskList struct with add(), remove(), close(), isEmpty(), isClosed(), pop() methods; replaced global task counters with registry-based lifecycle; updated Executor.yield() to accept expected_state and desired_state parameters; added timedWaitForReady/WithCallback with expected_state parameter; implemented atomic state transitions in waitForComplete and task registration/deregistration.
Awaitable list concurrency
src/core/ConcurrentAwaitableList.zig
Updated acquireMutationLock yield call from e.yield(.ready, .no_cancel) to e.yield(.ready, .ready, .no_cancel) to align with new yield semantics.
Synchronization primitives
src/sync/Condition.zig, src/sync/Mutex.zig, src/sync/ResetEvent.zig
Replaced CompactConcurrentQueue with ConcurrentQueue in all wait queues; introduced atomic preparing_to_wait state transitions before enqueueing; added conditional yield/push flows with pushOrTransition and pushUnless to prevent lost wakeups.
Concurrent queue implementation
src/utils/concurrent_queue.zig
Removed CompactConcurrentQueue type entirely; added pushUnless(forbidden_state, item) -> bool and pushOrTransition(from_state, to_state, item) -> PushOrTransitionResult public methods; extracted pushInternal() helper to support new atomic enqueue semantics.
Public API exports
src/utils.zig
Removed public CompactConcurrentQueue alias export.

Sequence Diagram(s)

sequenceDiagram
    participant Task as Task/Awaitable
    participant Executor
    participant Queue as ConcurrentQueue
    participant Coro as Coroutine

    rect rgb(200, 220, 240)
    Note over Task,Coro: Old: Simple push-and-yield (potential lost wakeup)
    Task->>Coro: check state (ready/waiting)
    Task->>Queue: push(wait_node)
    Task->>Executor: yield(.waiting, .no_cancel)
    Executor-->>Task: (may resume after push)
    end

    rect rgb(240, 220, 200)
    Note over Task,Coro: New: Atomic transition preventing lost wakeups
    Task->>Coro: state.store(.preparing_to_wait)
    Task->>Queue: pushOrTransition(.preparing_to_wait, .ready, node)<br/>or pushUnless(.ready, node)
    alt Pushed successfully
        Task->>Executor: yield(.preparing_to_wait, .waiting, .no_cancel)
        Executor->>Coro: state transition attempt
    else Already set/transitioned
        Task-->>Task: Return immediately (ready)
    end
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Rationale: Heterogeneous, high-density changes across multiple subsystems—introduction of AnyTaskList with new lifecycle semantics, coroutine state machine expansion with atomic wrappers, multi-parameter yield signature changes affecting all call sites, and subtle race-condition fixes in sync primitives via new queue APIs. Requires careful reasoning for each cohort to verify correctness of atomic transitions and state machine invariants.

Possibly related PRs

Poem

🐰 A rabbit's ode to atomicity:
State machines dance in three-step grace,
preparing_to_wait finds lost wakeups' place,
With pushOrTransition and queues unified,
Lost races are caught, no more compile denied!
The task registry hops, keeping all in check—
Concurrency locks without a wreck! 🐇✨

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 pull request title "Move task registry to global Runtime storage with sentinel-based shutdown" directly and accurately describes the primary objective of the PR. According to the PR objectives, the main purpose is to refactor the task registry from per-Executor local storage to a single global registry on Runtime, replacing atomic fields with sentinel-encoded state in an AnyTaskList structure. The title is specific, concise, and uses meaningful terminology that clearly indicates the architectural change being made. While the PR includes supporting changes to the coroutine state machine, queue APIs, and sync primitives, these are enablers for the main objective which is properly captured in the title.
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 global-task-registry

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

🧹 Nitpick comments (1)
src/runtime.zig (1)

1292-1297: Defensive error handling for remote wakeup notification.

The code checks if remote_initialized before calling notify(), and logs a warning if notification fails. This is defensive:

  • The task is already in the remote queue, so the failure is not critical
  • The warning helps diagnose issues in production

However, consider whether debug printing is appropriate here, as it could be verbose under high contention or in failure scenarios.

If verbose warnings are a concern, you could:

  1. Rate-limit the warning (log once per N failures)
  2. Use a metric counter instead of printing
  3. Log at a lower level (e.g., trace instead of warn)

But this is a minor point—the current approach is reasonable for initial deployment.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2a1182a and 4246fec.

📒 Files selected for processing (11)
  • benchmarks/concurrent_queue_bench.zig (1 hunks)
  • benchmarks/echo_server.zig (1 hunks)
  • benchmarks/ping_pong.zig (1 hunks)
  • src/core/ConcurrentAwaitableList.zig (1 hunks)
  • src/coroutines.zig (3 hunks)
  • src/runtime.zig (25 hunks)
  • src/sync/Condition.zig (4 hunks)
  • src/sync/Mutex.zig (2 hunks)
  • src/sync/ResetEvent.zig (5 hunks)
  • src/utils.zig (0 hunks)
  • src/utils/concurrent_queue.zig (8 hunks)
💤 Files with no reviewable changes (1)
  • src/utils.zig
🔇 Additional comments (35)
benchmarks/ping_pong.zig (1)

27-27: LGTM! Explicit runtime configuration.

The change to explicitly pass .num_executors = null is consistent with the broader pattern across benchmarks and makes the configuration intent clear.

src/core/ConcurrentAwaitableList.zig (1)

146-146: LGTM! Updated yield signature for new state machine.

The yield call now correctly includes both expected_state and desired_state parameters (both .ready in this spin-wait context), aligning with the updated coroutine state machine semantics across the codebase.

benchmarks/echo_server.zig (1)

188-188: LGTM! Consistent with other benchmarks.

The explicit runtime configuration matches the pattern established in other benchmark files.

benchmarks/concurrent_queue_bench.zig (4)

174-175: LGTM! Simplified output after CompactConcurrentQueue removal.

The consolidated size reporting for ConcurrentQueue and StandardNode correctly reflects the removal of the compact queue variant.


179-179: LGTM! Updated benchmark naming.

The label now accurately reflects that only ConcurrentQueue is being benchmarked.


181-181: Excellent improvement! Adaptive thread count.

Using std.Thread.getCpuCount() instead of a hardcoded value makes the benchmark adapt to the actual system configuration, providing more meaningful results across different machines.


187-187: LGTM! Consistent naming.

The concurrent benchmark label correctly identifies the queue type being tested.

src/sync/Mutex.zig (3)

31-31: LGTM! Migration to ConcurrentQueue.

The replacement of CompactConcurrentQueue with ConcurrentQueue is consistent with the broader refactoring across the codebase and aligns with the new queue APIs (pushOrTransition, etc.).

Also applies to: 39-39, 41-41


77-87: Excellent race prevention with preparing_to_wait state!

The new atomic state machine correctly prevents the race where the mutex is unlocked between the tryTransition check and queue enqueue. The three-step approach is sound:

  1. Transition to preparing_to_wait before any queue operations
  2. Use pushOrTransition to atomically either enqueue or acquire if unlocked
  3. Restore ready state if the mutex was acquired via transition

This prevents the problematic state progression: unlocked -> has_waiters (skipping locked_once), which could lead to lost wakeups.


91-91: LGTM! Updated yield with atomic state transition.

The yield now correctly passes expected_state: .preparing_to_wait and desired_state: .waiting, ensuring the CAS inside yield will detect early wakeups (if state was changed from preparing_to_wait before suspension) and avoid unnecessary suspension.

src/coroutines.zig (3)

11-16: LGTM! New state machine properly supports atomic wait/wake protocol.

The addition of preparing_to_wait state enables a lost-wakeup-free protocol:

  • Task transitions to preparing_to_wait before enqueueing
  • If woken early, the atomic CAS in yield() will fail and skip suspension
  • Otherwise, atomically transitions preparing_to_wait → waiting

This is a well-known pattern for preventing race conditions in wait queues.


402-402: LGTM! Atomic state field enables safe concurrent state transitions.

Wrapping the state in std.atomic.Value allows lock-free coordination between the yielding task and the waker, which is essential for the new wait/wake protocol introduced in this PR.


421-421: LGTM! Atomic store with proper memory ordering.

Using .release ordering ensures that all writes made by the coroutine function are visible before the state becomes .dead, which is correct for this synchronization point.

src/sync/Condition.zig (3)

57-60: LGTM! Migration to ConcurrentQueue completed.

The switch from CompactConcurrentQueue to ConcurrentQueue aligns with the broader architectural changes in this PR. The new queue type provides the pushUnless and pushOrTransition APIs needed for the atomic wait/wake protocol.


90-107: LGTM! Correct implementation of the new wait protocol.

The sequence is correct:

  1. Atomically set state to preparing_to_wait (Line 91)
  2. Enqueue to wait queue (Line 94)
  3. Release mutex (Line 97)
  4. Atomic yield with CAS preparing_to_wait → waiting (Line 101)

If a signal arrives between enqueue and yield, the CAS will fail and the task won't suspend, preventing lost wakeups.


130-172: LGTM! Timed wait follows the same pattern.

The timedWait implementation correctly mirrors the atomic state transition protocol used in wait(), with the added timeout callback mechanism.

src/sync/ResetEvent.zig (4)

52-55: LGTM! Consistent migration to ConcurrentQueue.


59-66: LGTM! Clear documentation of sentinel states.

The comments clearly explain the state encoding using ConcurrentQueue sentinels:

  • sentinel0 = unset
  • sentinel1 = set
  • pointer = waiting (has waiters)

124-142: LGTM! Correct use of pushUnless to prevent invalid state transitions.

The pushUnless(is_set, ...) ensures that we only enqueue if the event is not already set. This prevents the invalid transition is_set → has_waiters and handles the race where the event is set between the initial check and the enqueue.

If pushUnless returns false (event was set), the code correctly resets the task state to .ready and returns immediately.


174-215: LGTM! Timed wait correctly implements the same protocol.

src/utils/concurrent_queue.zig (5)

200-228: LGTM! Good refactoring to separate concerns.

Extracting pushInternal makes the code more maintainable and allows the new pushUnless and pushOrTransition methods to reuse the enqueue logic after their respective checks/transitions.


230-283: LGTM! New APIs enable atomic wait/wake protocols.

The new methods are well-designed:

  • pushUnless: Conditionally pushes unless in a forbidden state (e.g., don't add waiters if already signaled)
  • pushOrTransition: Atomically either transitions state or pushes item, preventing invalid state transitions (e.g., unlocked → has_waiters without going through locked_once)
  • PushOrTransitionResult: Clear enum for distinguishing the outcome

These primitives enable the synchronization primitives (ResetEvent, Mutex, etc.) to implement correct, race-free wait/wake logic.


165-186: LGTM! Yielding prevents live-lock in contention.

The addition of std.Thread.yield() on spin overflow (Line 182) is important for multi-threaded scenarios where multiple threads may be contending for the mutation lock. Without yielding, high-priority threads could starve lower-priority threads.

The comment accurately describes the behavior.


357-395: LGTM! Defensive pointer saving prevents race conditions.

Lines 357-363 save the prev and next pointers before clearing them, then use the saved values for the removal logic. This prevents data races if another thread concurrently calls remove() on the same item—the second call will see null pointers and fail the early exit checks at lines 342-350.

This is a good defensive programming practice for lock-free data structures.


406-456: LGTM! Complex but correct state-aware pop operation.

The popOrTransition logic handles multiple cases:

  1. From sentinel → transition to target sentinel (Lines 413-416)
  2. Already at target sentinel → no-op (Lines 419-422)
  3. Unexpected sentinel → defensive null return (Lines 425-430)
  4. Has items → pop and transition/update accordingly (Lines 432-455)

The defensive checks at lines 419-430 improve robustness. The logic is complex but appears correct for the sentinel-based state encoding used throughout the PR.

src/runtime.zig (10)

411-468: LGTM! Well-designed global task registry with sentinel-based shutdown.

The AnyTaskList encapsulates the task lifecycle management with clear state encoding:

  • sentinel0 (empty_open): No tasks, accepting spawns
  • sentinel1 (empty_closed): No tasks, runtime shutting down
  • Pointer: Has tasks, accepting spawns

Key methods are well-designed:

  • add() returns error.Closed if shutting down (prevents spawns during shutdown)
  • close() is idempotent and returns error.NotEmpty if tasks remain
  • remove(), isEmpty(), isClosed(), pop() provide the complete lifecycle API

This is a significant improvement over separate atomic counters, as it combines spawn gating and task tracking in one lock-free structure.


182-202: LGTM! Correct integration of atomic wait protocol in waitForComplete.

The sequence properly implements the new protocol:

  1. Transition to preparing_to_wait (Line 183)
  2. Enqueue to wait list (Line 185)
  3. Double-check completion (Lines 188-194) with state rollback on early completion
  4. Atomic yield preparing_to_wait → waiting (Line 198)

The double-check with rollback to .ready (Line 192) correctly handles the race where completion happens during enqueue.


330-359: LGTM! Atomic state swap elegantly handles the waiting/preparing_to_wait distinction.

The logic is correct:

  1. Atomically swap to .ready and observe old state (Line 346)
  2. If old state was .waiting, the task is suspended—schedule it (Line 351)
  3. If old state was .preparing_to_wait, the task hasn't yielded yet—it will observe .ready and skip suspension, so no scheduling needed (Lines 352-354)
  4. Otherwise, unexpected state—panic (Lines 356-358)

This correctly implements the protocol where a task in preparing_to_wait can be woken before it suspends.


1035-1089: LGTM! Atomic CAS prevents lost wakeups in yield.

The critical CAS at lines 1052-1061:

  • Attempts expected_state → desired_state transition
  • On failure with actual_state == .ready, skips suspension (early wakeup case)
  • On failure with unexpected state, panics (bug detection)

This ensures that if resumeTask() sets the state to .ready after we set preparing_to_wait but before we yield, the CAS fails and we don't suspend—preventing a lost wakeup.

The panic on unexpected states (Line 1059) is appropriate for catching bugs during development.


1148-1163: LGTM! Clean shutdown helper with correct race handling.

The maybeShutdown() helper encapsulates the shutdown logic:

  1. Check if task list is empty (Line 1149)
  2. Try to close registry (atomic empty_open → empty_closed transition, Line 1151)
  3. On success, set shutdown flag and wake all executors (Lines 1153-1158)
  4. On failure (race with task addition or concurrent close), do nothing (Lines 1159-1161)

The if (self.runtime_ptr.tasks.close()) idiom correctly handles races:

  • If another executor closes first, this one sees empty_closed and close() returns success (idempotent per AnyTaskList.close() docs)
  • If tasks were added, close() returns error.NotEmpty and shutdown is aborted

997-999: LGTM! Spawn correctly registers task with shutdown check.

Adding to the global registry (Line 998) with errdefer cleanup (Line 999) ensures:

  1. Spawn fails with error.Closed if runtime is shutting down (via AnyTaskList.add())
  2. If subsequent spawn operations fail (e.g., scheduling), task is removed from registry

This maintains the invariant that all tasks in the registry are either running or scheduled.


1180-1182: LGTM! Immediate shutdown check prevents hang on empty start.

Calling maybeShutdown() at executor startup ensures that if the runtime is started with no tasks, it immediately transitions to shutdown rather than blocking indefinitely in the event loop. This is a nice usability improvement.


1226-1232: LGTM! Task completion cleanup and shutdown check.

After marking a task complete, the code:

  1. Removes it from the global registry (Line 1227)
  2. Releases the runtime's reference (Line 1228)
  3. Checks if this was the last task and maybe initiates shutdown (Line 1232)

This ensures the runtime shuts down cleanly when all tasks complete.


1645-1648: LGTM! Deinit properly drains remaining tasks.

The cleanup loop ensures all tasks remaining in the registry are released, preventing memory leaks. This handles the case where the runtime is deinitialized while tasks are still registered (e.g., due to external shutdown).


1667-1670: LGTM! Spawn methods correctly check shutdown state.

Both spawn() and spawnBlocking() check tasks.isClosed() before attempting to spawn, returning error.RuntimeShutdown if the runtime is shutting down. This prevents new tasks from being created during shutdown, which could cause hangs or undefined behavior.

Also applies to: 1697-1700

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