Repository navigation
Add SimpleWaitQueue for mutex-protected use cases - #93
Conversation
Introduces SimpleWaitQueue, a non-atomic wait queue designed for use under external synchronization (e.g., mutex). This provides better performance and simpler code compared to WaitQueue when atomics and mutation spinlocks are unnecessary. Updates Channel to use SimpleWaitQueue instead of WaitQueue, since all queue access is already protected by the channel's mutex. This eliminates unnecessary atomic operations and spinloops. Changes: - Add SimpleWaitQueue implementation to wait_queue.zig - Add comprehensive tests for SimpleWaitQueue - Update Channel to use SimpleWaitQueue for receiver/sender queues - All existing tests pass without modification
|
Warning Rate limit exceeded@lalinsky has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 11 minutes and 12 seconds before requesting another review. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📒 Files selected for processing (2)
WalkthroughReplaces Channel's atomic wait-queues with a new non-atomic SimpleWaitQueue primitive and updates Channel wake/pop logic to use mutex-protected loops. Adds SimpleWaitQueue implementation and tests validating push/pop/remove and empty semantics. Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes
Possibly related PRs
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
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: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/sync/channel.zig (1)
269-280: Bug: Draining wait queues after close() violates SimpleWaitQueue’s “must hold lock” contract
receiver_queue.pop()andsender_queue.pop()are called without holdingself.mutex. That was OK with the atomic WaitQueue, but it’s unsafe with SimpleWaitQueue and can race with cancellations (remove()) or any in-flight enqueue. Fix by popping under the mutex, waking outside the lock.Apply this diff:
self.mutex.unlock(); - // Wake all receivers so they can see the channel is closed - while (self.receiver_queue.pop()) |node| { - node.wake(); - } - - // Wake all senders so they can see the channel is closed - while (self.sender_queue.pop()) |node| { - node.wake(); - } + // Drain receivers under lock, wake outside to avoid re-entrancy + while (true) { + self.mutex.lock(); + const r = self.receiver_queue.pop(); + self.mutex.unlock(); + if (r) |node| node.wake() else break; + } + + // Drain senders under lock, wake outside to avoid re-entrancy + while (true) { + self.mutex.lock(); + const s = self.sender_queue.pop(); + self.mutex.unlock(); + if (s) |node| node.wake() else break; + }
🧹 Nitpick comments (2)
src/utils/wait_queue.zig (1)
111-140: Defensive membership check in Debug to avoid unlinking foreign/stale nodesToday we rely on prev/next null checks to decide “not in list.” In Debug, we already track
in_list— use it to fail fast and avoid unlinking if someone passes a node from another queue or with stale pointers.Apply this diff to add a Debug-only guard at the start of remove():
pub fn remove(self: *Self, item: *T) bool { + if (builtin.mode == .Debug) { + if (!item.in_list) return false; + } // Check if item is in the list by verifying pointers if (item.prev == null and self.head != item) { return false; } if (item.next == null and self.tail != item) { return false; } - if (builtin.mode == .Debug) { - item.in_list = false; - } + if (builtin.mode == .Debug) item.in_list = false;src/sync/channel.zig (1)
143-151: Minor TOCTOU: readclosedunder the lock in tryReceive()We unlock before checking
closed, so a close between unlock and the check can return ChannelEmpty instead of ChannelClosed. Read it while holding the mutex and branch after unlock.Apply this diff:
- if (self.count == 0) { - self.mutex.unlock(); - if (self.closed) { - return error.ChannelClosed; - } - return error.ChannelEmpty; - } + if (self.count == 0) { + const is_closed = self.closed; + self.mutex.unlock(); + return if (is_closed) error.ChannelClosed else error.ChannelEmpty; + }
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
src/sync/channel.zig(2 hunks)src/utils/wait_queue.zig(3 hunks)
🔇 Additional comments (4)
src/utils/wait_queue.zig (3)
64-82: Push path looks solidPointer init and head/tail updates are correct; debug guard prevents double-enqueue. No issues.
87-106: Pop correctnessFIFO, head/tail maintenance, and debug in_list handling are correct. Good cleanup of node links.
588-731: Tests cover the core SimpleWaitQueue behaviorsBasic, remove semantics, head/tail removal, and .empty initializer are exercised. Nice coverage.
src/sync/channel.zig (1)
3-3: Switch to SimpleWaitQueue is appropriate hereChannel ops are already mutex-protected; replacing atomic WaitQueue with SimpleWaitQueue is the right call. No issues with the field/type changes.
Also applies to: 55-57
Read closed flag while holding mutex to avoid race condition where channel could be closed between unlock and the check, incorrectly returning ChannelEmpty instead of ChannelClosed.
Pop wait queue nodes under mutex protection to comply with SimpleWaitQueue's requirement for external synchronization. The previous code called pop() without holding the lock, which could race with concurrent remove() calls during cancellation. Each node is now popped while holding the lock, then woken after release to avoid holding the lock during wake operations.
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (4)
src/sync/channel.zig (4)
3-3: Good swap to SimpleWaitQueue; mutex discipline looks consistent.All push/pop/remove sites in this file run under
self.mutex; wakes happen after unlock. That matches the non-atomic contract.Add an explicit invariant comment near the fields to prevent future misuse.
55-56: Document the synchronization invariant on waiter queues.Make it hard to misuse by stating “all mutations under self.mutex; wake after unlock” right where the fields live.
Apply this doc-only diff:
mutex: std.Thread.Mutex = .{}, - receiver_queue: SimpleWaitQueue(WaitNode) = .empty, - sender_queue: SimpleWaitQueue(WaitNode) = .empty, + /// Waiter queues; mutate only while holding `self.mutex`. Never wake under the lock. + receiver_queue: SimpleWaitQueue(WaitNode) = .empty, + sender_queue: SimpleWaitQueue(WaitNode) = .empty,
270-279: Drain-and-wake pattern is correct; consider a single-lock drain to reduce churn.Current loop pops under lock and wakes after unlock (correct). If there can be many waiters, consider adding
takeAll()(orswapWithEmpty()) toSimpleWaitQueuesoclose()can:
- lock once, move all nodes to a local list, unlock;
- wake them outside the lock.
This keeps correctness and reduces lock/unlock overhead.
I can sketch
takeAll()forSimpleWaitQueueand wire this up if you want.
283-291: Same note for sender drain: single-lock drain could help under load.Mirror the receiver-side suggestion here for symmetry and fewer lock transitions.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/sync/channel.zig(4 hunks)
🔇 Additional comments (2)
src/sync/channel.zig (2)
146-149: LGTM: snapshot closed under lock.Capturing
closedbefore unlock keeps the empty/closed decision atomic with the emptiness check. Clean and correct.
55-56: Verification complete—both invariants hold.External references are confined to
src/sync/channel.zigonly; no cross-file access to the queue fields. AllSimpleWaitQueueoperations (push, pop, remove) are consistently guarded by mutex locks—eitherself.mutexorself.channel.mutexwith the pattern: lock → queue op → unlock. The field type change is safe.
Adds popAll() method to SimpleWaitQueue that swaps the entire queue with an empty one in a single operation. This encapsulates the pattern of draining all items from a queue without repeated locking. Updates Channel.close() to use popAll() instead of manually swapping with .empty, reducing the number of lock/unlock cycles from O(n) to O(1) where n is the number of waiting tasks.
Summary
Introduces
SimpleWaitQueue, a non-atomic wait queue designed for use under external synchronization (e.g., mutex). This provides better performance and simpler code compared toWaitQueuewhen atomics and mutation spinlocks are unnecessary.Updates
Channelto useSimpleWaitQueueinstead ofWaitQueue, since all queue access is already protected by the channel's mutex.Changes
SimpleWaitQueueimplementation towait_queue.zigSimpleWaitQueue(4 tests)Channelto useSimpleWaitQueuefor receiver/sender queuesBenefits
Implementation
SimpleWaitQueueis a straightforward doubly-linked list with:Perfect for use cases like
Channelwhere a mutex already protects all queue operations.