Repository navigation
Add xev.ThreadPool integration - #9
Conversation
- Add compile-time backend detection using @Hasfield(xev.Loop, "thread_pool") - Auto-enable ThreadPool for backends that need it (epoll, kqueue) - Heap-allocate ThreadPool for stable pointer address - Add RuntimeOptions with ThreadPoolOptions configuration - Update all examples and tests for new Runtime.init() signature - Add smoke test for ThreadPool functionality Backends supported: - epoll (Linux): ThreadPool auto-enabled - kqueue (macOS/FreeBSD): ThreadPool auto-enabled - io_uring (Linux): ThreadPool auto-disabled - iocp (Windows): ThreadPool auto-disabled - wasi_poll (WASI): ThreadPool auto-disabled
|
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. WalkthroughAdds RuntimeOptions with optional thread pool support, changes Runtime.init signature to accept options, wires thread pool into xev.Loop with conditional creation/shutdown, updates deinit accordingly, and adjusts examples/tests to pass an empty options struct. Also updates .gitignore to ignore .claude, .zig-cache, and zig-out. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor App as Application
participant RT as Runtime.init
participant XEV as xev.Loop
participant TP as xev.ThreadPool
App->>RT: init(allocator, options)
RT->>RT: detect backendNeedsThreadPool
alt ThreadPool enabled (options.thread_pool.enabled or backend)
RT->>TP: create(config: max_threads, stack_size)
TP-->>RT: pointer
RT->>XEV: create(loop_opts with thread_pool)
else No ThreadPool
RT->>XEV: create(loop_opts without thread_pool)
end
RT-->>App: Runtime{ loop, thread_pool=? }
note over RT,XEV: New: conditional creation and wiring of ThreadPool into Loop
sequenceDiagram
autonumber
actor App as Application
participant RT as Runtime.deinit
participant XEV as xev.Loop
participant TP as xev.ThreadPool
App->>RT: deinit()
RT->>XEV: shutdown & deinit loop
alt thread_pool present
RT->>TP: shutdown()
RT->>TP: deinit()
RT->>RT: free thread_pool
else
RT->>RT: no-op for thread_pool
end
RT-->>App: done
note over RT,TP: New: graceful pool teardown before full runtime teardown
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
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 |
There was a problem hiding this comment.
Actionable comments posted: 3
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (11)
.gitignore(1 hunks)examples/future_demo.zig(1 hunks)examples/mutex_demo.zig(1 hunks)examples/producer_consumer.zig(1 hunks)examples/sleep.zig(1 hunks)examples/tcp_client.zig(1 hunks)examples/tcp_echo_server.zig(1 hunks)examples/tls_demo.zig(1 hunks)examples/udp_echo.zig(1 hunks)src/runtime.zig(5 hunks)src/sync.zig(5 hunks)
🔇 Additional comments (5)
.gitignore (1)
1-3: Ignore the new Zig build artifactsAdding entries for
.claude,.zig-cache, andzig-outkeeps transient tooling outputs out of version control. Nice housekeeping.examples/tcp_client.zig (1)
33-34: Runtime.init options usage aligns with new APIPassing the empty options struct keeps the example compatible with the expanded
Runtime.initsignature without altering behavior. Looks good.examples/mutex_demo.zig (1)
28-29: Example updated for RuntimeOptionsSupplying
.{}here keeps the demo in sync with the updated runtime initializer while preserving existing semantics.examples/tcp_echo_server.zig (1)
53-55: Echo server stays compatible with new init signatureThe empty options argument ensures the example compiles against the revised runtime API with no functional change.
src/sync.zig (1)
166-168: Tests cover the new Runtime.init contractUpdating the test harness to pass
.{}keeps it aligned with the newRuntimeOptionsparameter and maintains the existing test coverage.
This file was not supposed to be included in the ThreadPool integration PR. Co-authored-by: Lukáš Lalinský <[email protected]>
Properly shutdown and deinit thread pool before destroying on init failure to prevent leaking worker threads and resources. Co-authored-by: Lukáš Lalinský <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (4)
src/runtime.zig (4)
15-18: Detect against Loop.Config, not Loop, for better portabilitySafer to key auto-detection off the init config shape rather than the runtime struct.
-fn backendNeedsThreadPool() bool { - return @hasField(xev.Loop, "thread_pool"); -} +fn backendNeedsThreadPool() bool { + return @hasField(xev.Loop.Config, "thread_pool"); +}
20-29: Make options future-proof and validate inputs
- Consider a tri-state to disambiguate auto vs force-enable vs disable.
- Validate non-null values (e.g., max_threads >= 1).
Example shape:
pub const RuntimeOptions = struct { - thread_pool: ThreadPoolOptions = .{}, + thread_pool: ThreadPoolOptions = .{}, pub const ThreadPoolOptions = struct { - enabled: bool = backendNeedsThreadPool(), + // auto=detect, enabled=force on, disabled=force off + mode: enum { auto, enabled, disabled } = .auto, max_threads: ?u32 = null, // null = CPU count stack_size: ?u32 = null, // null = default stack size }; };If you prefer to keep boolean, add a small validator in init:
if (options.thread_pool.max_threads != null and options.thread_pool.max_threads.? == 0) return error.InvalidThreadCount;Would you like me to wire the validator for you?
287-308: Teardown order is correct; consider small cleanups
- Shutdown before loop teardown, then deinit+free after loop: good.
- Optional: null out
self.thread_poolafter destroy to guard accidental double deinit patterns.if (self.thread_pool) |tp| { tp.deinit(); self.allocator.destroy(tp); + self.thread_pool = null; }
457-473: Augment tests to cover auto and disable modesThis smoke test is good. Add:
- Auto mode:
const rt = try Runtime.init(testing.allocator, .{});thencomptime if (@hasField(xev.Loop.Config,"thread_pool")) testing.expect(rt.thread_pool != null) else testing.expect(rt.thread_pool == null).- Disabled mode: assert
thread_pool == nulleven when backend supports it.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/runtime.zig(5 hunks)
🔇 Additional comments (3)
src/runtime.zig (3)
247-247: Heap pointer for stability across moves: LGTMThe nullable heap-allocated ThreadPool pointer is the right choice to keep a stable address if Runtime moves.
268-272: Nice: fixed the error-path leak by shutting down + deinit before destroyThis resolves the earlier review about leaking worker threads/resources on init failure.
257-278: Gate.thread_poolinxev.Loop.init- // Initialize libxev loop with optional ThreadPool - const loop = try xev.Loop.init(.{ - .thread_pool = thread_pool, - }); + // Initialize libxev loop with optional ThreadPool (only when the field exists) + var loop: xev.Loop = undefined; + comptime if (@hasField(xev.Loop.Config, "thread_pool")) { + loop = try xev.Loop.init(.{ .thread_pool = thread_pool }); + } else { + loop = try xev.Loop.init(.{}); + }Follow-ups—please verify against your pinned libxev version:
• Doesxev.Loop.Configinclude athread_poolfield only for epoll/kqueue backends?
• What is the exact signature ofxev.ThreadPool.init—does it return an error?
• Is a ThreadPool required for epoll/kqueue and simply ignored on io_uring/iocp/wasi?
| pub fn init(allocator: Allocator, options: RuntimeOptions) !Runtime { | ||
| // Initialize ThreadPool if enabled | ||
| var thread_pool: ?*xev.ThreadPool = null; | ||
| if (options.thread_pool.enabled) { | ||
| thread_pool = try allocator.create(xev.ThreadPool); | ||
|
|
||
| var config = xev.ThreadPool.Config{}; | ||
| if (options.thread_pool.max_threads) |max| config.max_threads = max; | ||
| if (options.thread_pool.stack_size) |size| config.stack_size = size; | ||
| thread_pool.?.* = xev.ThreadPool.init(config); | ||
| } | ||
| errdefer if (thread_pool) |tp| { | ||
| tp.shutdown(); | ||
| tp.deinit(); | ||
| allocator.destroy(tp); | ||
| }; | ||
|
|
||
| // Initialize libxev loop with optional ThreadPool | ||
| const loop = try xev.Loop.init(.{ | ||
| .thread_pool = thread_pool, | ||
| }); | ||
|
|
||
| return Runtime{ | ||
| .allocator = allocator, | ||
| .loop = loop, | ||
| .thread_pool = thread_pool, | ||
| .main_context = undefined, | ||
| }; | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major
🧩 Analysis chain
Verify callsites updated for new init signature
Since Runtime.init now requires options, ensure all callsites pass the second argument.
🏁 Script executed:
#!/bin/bash
# Find Runtime.init callsites missing the options argument (heuristic).
rg -nP --no-heading '\bRuntime\.init\s*\(\s*[^,)\n]+\s*\)' -C2Length of output: 2757
Add missing options parameter to all Runtime.init callsites
- src/udp.zig:181
- src/tcp.zig:425, 490, 550, 612, 675, 737
- src/file.zig:257, 297, 341
- README.md:24
Each of these should pass a RuntimeOptions value (e.g. `.{} for defaults) as the second argument.
🤖 Prompt for AI Agents
In src/runtime.zig around lines 257 to 285, Runtime.init now requires a second
parameter of type RuntimeOptions but multiple callsites were not updated; update
every Runtime.init call listed in the review — src/udp.zig:181; src/tcp.zig:425,
490, 550, 612, 675, 737; src/file.zig:257, 297, 341; and the README example at
line 24 — to pass a RuntimeOptions value (use .{} for defaults or a constructed
RuntimeOptions as appropriate) as the second argument, ensuring the call
signatures and any tests/docs compile with the new parameter.
Summary
Adds intelligent ThreadPool integration to the Runtime with automatic backend detection.
Key Features
@hasField(xev.Loop, "thread_pool")to detect at compile-time which backends need ThreadPool.{}options parameterBackend Support
API Examples
Default (auto-detection):
Custom configuration:
Explicit disable:
Changes Made
RuntimeOptionsandThreadPoolOptionsconfiguration structsRuntime.init()signature to accept options parameterTest Plan
Ready for review and testing across different platforms.
Summary by CodeRabbit
New Features
Refactor
Tests
Chores