Skip to content

Add spawnBlocking API for thread pool execution - #16

Merged
lalinsky merged 1 commit into
mainfrom
feat/spawn-blocking
Oct 1, 2025
Merged

lalinsky merged 1 commit into
mainfrom
feat/spawn-blocking

Conversation

@lalinsky

@lalinsky lalinsky commented Oct 1, 2025 •

Copy link
Copy Markdown
Owner

Summary

Implements spawnBlocking() to run blocking operations on a thread pool without blocking the async runtime.

Implementation Details

  • New types: AnyBlockingTask, BlockingTask(T) for thread pool tasks
  • Thread pool integration: Uses xev.ThreadPool with async completion notifications via xev.Async
  • Thread-safe completion: MPSC queue for handling completions from worker threads
  • Event loop optimization: Uses .no_wait mode when work is pending to avoid unnecessary blocking
  • Memory management: Proper ref counting (1 ref for JoinHandle, 1 ref for runtime) with automatic cleanup
  • Test coverage: Includes smoke test for basic functionality

Example Usage

var handle = try runtime.spawnBlocking(blockingWork, .{arg});
defer handle.deinit();
const result = handle.join();

Testing

All tests pass, including the new spawnBlocking smoke test.

Summary by CodeRabbit

  • New Features
    • Added support for running blocking tasks on a thread pool, with handles to await/join results like async tasks.
  • Performance
    • Improved runtime responsiveness by optimizing the event loop when blocking work is pending.
  • Tests
    • Added a smoke test verifying end-to-end execution and result retrieval for blocking tasks.
  • Chores
    • Updated dependency to expose an internal queue utility publicly.
    • Refined initialization and teardown to account for new blocking task components.

@coderabbitai

coderabbitai Bot commented Oct 1, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds blocking task support to the runtime using a thread pool, new awaitable/task kinds, wakeup/completion plumbing, and a spawnBlocking API. Updates Runtime fields and run loop handling, introduces callback/drain functions, and adds a smoke test. Exposes queue_mpsc in vendor libxev as a public constant.

Changes

Cohort / File(s) Summary
Runtime: blocking tasks & scheduling
src/runtime.zig
Introduces AwaitableKind.blocking_task, AnyBlockingTask, BlockingTask(T); extends Task/JoinHandle for blocking; adds Runtime fields (blocking_completions, async_wakeup, async_completion, blocking_initialized); implements spawnBlocking, threadPoolCallback, drainBlockingCompletions; adjusts run loop mode; adds blocking task smoke test; updates init/teardown.
Vendor: public API exposure
vendor/libxev/src/main.zig
Adds pub const queue_mpsc = @import("queue_mpsc.zig"); to expose MPSC queue module publicly.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant U as User Code
  participant RT as Runtime
  participant TP as ThreadPool
  participant EV as xev.Async/xev.Loop
  participant DR as drainBlockingCompletions

  U->>RT: spawnBlocking(func, args)
  RT->>TP: enqueue task with threadPoolCallback
  Note over TP: Blocking work executes
  TP-->>RT: completion enqueued (MPSC)
  TP->>EV: async_wakeup.fire()
  EV-->>RT: completion ready (async_completion)
  RT->>DR: drainBlockingCompletions(...)
  DR-->>U: resume waiter(s), deliver result
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

I spun a thread and hopped along,
Queues went cheep, the wakeups strong—
Tasks that block now find their way,
Pool to loop to bright new day.
With tiny paws I press “run” quick,
Results pop out—ah, that’s the trick! 🐇⚙️

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 succinctly describes the main change of introducing the spawnBlocking API for executing blocking tasks on the thread pool, matching the core objective of the pull request while remaining clear and specific.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/spawn-blocking

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.

Implements spawnBlocking() to run blocking operations on a thread pool
without blocking the async runtime:

- New types: AnyBlockingTask, BlockingTask(T) for thread pool tasks
- Thread pool integration via xev.ThreadPool with async completion notifications
- MPSC queue for thread-safe completion handling from worker threads
- Event loop optimization: uses .no_wait mode when work is pending
- Proper ref counting: 1 ref for JoinHandle, 1 ref for runtime completion
- Memory safety: automatic cleanup via destroy_fn callback
- Test coverage: basic spawnBlocking smoke test

Example usage:
```zig
var handle = try runtime.spawnBlocking(blockingWork, .{arg});
defer handle.deinit();
const result = handle.join();
```
@lalinsky
lalinsky force-pushed the feat/spawn-blocking branch from 4d105ed to 2e6657a Compare October 1, 2025 10:28
@lalinsky
lalinsky changed the base branch from refactor/awaitable-anytask-split to main October 1, 2025 10:28
@lalinsky

lalinsky commented Oct 1, 2025

Copy link
Copy Markdown
Owner Author

@CodeRabbit review

@coderabbitai

coderabbitai Bot commented Oct 1, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6cd7d16 and 2e6657a.

📒 Files selected for processing (2)
  • src/runtime.zig (8 hunks)
  • vendor/libxev/src/main.zig (1 hunks)

Comment thread src/runtime.zig Resolved
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