Repository navigation
Fix thread pool shutdown order - #534
Conversation
Thread-pool completion callbacks wake the owning event loop (writing its eventfd). The worker publishes the result and then calls loop.wake() as two separate steps, so it can be preempted in between; the loop can finish and be torn down before the trailing wake(), which then writes to a closed eventfd (eventfd_write: .BADF). Fixes #524. The invariant is that the loop must outlive the pool's threads. Previously stop() only signalled shutdown and only deinit() joined, so nothing guaranteed the pool was quiescent before a loop was closed. - ThreadPool.stop() now drops queued work, refuses new submissions, and joins all worker threads (idempotent). After it returns no completion callback can run. The pool object stays valid; submit() drops work once stopped. - ThreadPool.deinit() is now just stop() + free the workers list. - Runtime.deinit() stops/joins the pool first (all loops still alive), then shuts down executors, then deinits the pool, then deinits executors. - Tests reordered to stop() the pool before deinit'ing the loop; blocker-based cancel tests unblock the worker before the join.
|
Caution Review failedPull request was closed or merged during review No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughThread pool shutdown now runs through an idempotent ChangesThread pool shutdown ordering
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/ev/thread_pool.zig (1)
145-167: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winApply the shutdown guard before inline execution too.
When
builtin.single_threadedormax_threads == 0, Line 146 runs work inline before the new shutdown check at Line 162. That meanssubmit()afterstop()still executes the work and completion callback in the disabled-pool mode.Proposed fix
pub fn submit(self: *ThreadPool, work: *Work) void { + self.queue_mutex.lock(); + const shutdown = self.shutdown; + self.queue_mutex.unlock(); + if (shutdown) return; + if (builtin.single_threaded or self.max_threads == 0) {🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/ev/thread_pool.zig` around lines 145 - 167, The shutdown check in ThreadPool.submit currently happens only on the queued path, so inline execution still runs after stop() when builtin.single_threaded or max_threads == 0. Move the self.shutdown guard to the start of submit() before the inline-work branch, and return early there as well so work.func, work.c.setResult/setError, and completion_fn are skipped once the pool is shut down.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/ev/thread_pool.zig`:
- Around line 121-128: The ThreadPool stop path currently only sets shutdown in
stop(), but leaves pending items in self.queue, which can still be canceled
later and invoke completion_fn after shutdown. Update ThreadPool.stop to fully
drain or detach any queued work before releasing queue_mutex, using the existing
queue/shutdown handling in ThreadPool.cancel and the queue links so no callbacks
can fire after stop. Make sure the stop() and cancel() paths preserve the
no-callback-after-stop invariant by preventing any remaining queued completion
from being removed and executed after shutdown.
---
Outside diff comments:
In `@src/ev/thread_pool.zig`:
- Around line 145-167: The shutdown check in ThreadPool.submit currently happens
only on the queued path, so inline execution still runs after stop() when
builtin.single_threaded or max_threads == 0. Move the self.shutdown guard to the
start of submit() before the inline-work branch, and return early there as well
so work.func, work.c.setResult/setError, and completion_fn are skipped once the
pool is shut down.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 8ab11529-35d6-403f-91c6-a7790e5df39c
📒 Files selected for processing (5)
src/ev/test/cancel.zigsrc/ev/test/fs.zigsrc/ev/test/thread_pool.zigsrc/ev/thread_pool.zigsrc/runtime.zig
After stop() joins the workers, items submitted but never picked up can remain linked in the queue. A later cancel() could remove one and invoke its completion_fn (waking a loop being torn down), breaking the "no callback after stop" invariant. Drain the queue under the lock so this can't happen and the documented "drop any queued work" holds.
Fixes #524.
Problem
Thread-pool completion callbacks reach back into the event loop and write its eventfd. In
loopLinkedWorkCompletethe worker thread first publishes the result (work_completions.push) and then callsloop.wake()→backend.wake()→eventfd_write. These are two separate steps, so the worker can be preempted between them. Meanwhile the loop observes the published completion, finishes, and gets torn down — and the worker's trailingwake()then writes to a closed eventfd:The violated invariant is that the loop must outlive the thread pool's threads. The old
ThreadPool.stop()only signalled shutdown; onlydeinit()joined the threads. So nothing guaranteed the pool was quiescent before a loop was closed — neither in the failing test nor inRuntime.deinit(which closed loops atshutdownWorkers()/main_executor.deinit()while the pool wasn't joined until later).Fix
ThreadPool.stop()now performs the full hard stop: set shutdown, drop queued work, refuse new submissions, and join all worker threads (idempotent). After it returns, no worker thread exists, so no completion callback can fire. The pool object stays valid untildeinit().submit()drops work when shutdown is set (also prevents a post-stopspawnThread), so executors still tearing down can safely call into it.ThreadPool.deinit()is now juststop()+ free the workers list.Runtime.deinit()reordered to: stop+join the pool (all loops still alive) → shut down executors → deinit pool → deinit executors.stop()-ed (joined) beforeloop.deinit(); the blocker-based cancel tests unblock the worker before the join so it can't deadlock.Behavior note
submit()afterstop()now silently drops the work without firing its completion. This is intentional for shutdown ("all tasks are dropped"); in practice nothing submits post-stop since all tasks are already complete.Testing
-Dbackend=epoll).cancel: work before run(the reported failure) and the cancel/fs/ThreadPool groups pass underaarch64-linuxqemu with epoll. (io_uring is unavailable under qemu; the original CI failure was on the epoll path.)