Skip to content

Add SimpleWaitQueue for mutex-protected use cases - #93

Merged
lalinsky merged 4 commits into
mainfrom
add-simple-wait-queue
Oct 28, 2025
Merged

lalinsky merged 4 commits into
mainfrom
add-simple-wait-queue

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

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 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.

Changes

  • Add SimpleWaitQueue implementation to wait_queue.zig
  • Add comprehensive tests for SimpleWaitQueue (4 tests)
  • Update Channel to use SimpleWaitQueue for receiver/sender queues
  • All existing tests pass without modification (141 tests)

Benefits

  • Simpler code: No complex atomic memory ordering required
  • Better performance: Eliminates atomic operations and spinloops when accessing wait queues under mutex protection
  • Clearer design: The mutex provides all synchronization, making the synchronization model explicit and easier to understand

Implementation

SimpleWaitQueue is a straightforward doubly-linked list with:

  • No atomic operations
  • No mutation spinlock
  • No sentinel states
  • O(1) push, pop, and remove operations

Perfect for use cases like Channel where a mutex already protects all queue operations.

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
@coderabbitai

coderabbitai Bot commented Oct 28, 2025 •

Copy link
Copy Markdown
Contributor

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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.

📥 Commits

Reviewing files that changed from the base of the PR and between a33bfac and 1e3107f.

📒 Files selected for processing (2)
  • src/sync/channel.zig (4 hunks)
  • src/utils/wait_queue.zig (3 hunks)

Walkthrough

Replaces 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

Cohort / File(s) Summary
Wait queue primitive
src/utils/wait_queue.zig
Added pub fn SimpleWaitQueue(comptime T: type) type — a non-atomic doubly-linked-list wait-queue with O(1) push/pop/remove, isEmpty, and an empty initializer. Debug builds track node in_list. Expanded tests cover basic ops, remove semantics, head/tail edge cases, and empty initializer behavior.
Channel integration & wake logic
src/sync/channel.zig
Switched receiver_queue and sender_queue fields from WaitQueue(WaitNode) to SimpleWaitQueue(WaitNode) and updated import. Rewrote close/wake logic to repeatedly pop-and-wake nodes under the mutex to avoid races with concurrent removals; simplified fast-path receive return via ternary for closed vs empty.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • Review correctness of SimpleWaitQueue list invariants (empty, single-node, head/tail removal, duplicate removal) and debug in_list tracking.
  • Verify Channel's new mutex-protected pop-and-wake loops avoid races and maintain intended semantics (no deadlocks, correct wake ordering).
  • Confirm tests exercise edge cases and that changing from atomic to non-atomic queue is safe given Channel's synchronization model.

Possibly related PRs

Poem

Nodes line up where atoms once stood,
Mutex hums low, the list does good.
Pop, wake, repeat — no races today,
Simple links guide the waiting-way. 🔗

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title Check ✅ Passed The PR title "Add SimpleWaitQueue for mutex-protected use cases" directly captures the core change: introducing a new SimpleWaitQueue implementation designed for mutex-protected scenarios. The title aligns with both the primary objective (adding SimpleWaitQueue) and the motivation (external synchronization via mutex), making it clear and specific rather than vague. A reviewer scanning the commit history would immediately understand the changeset focuses on a new wait-queue variant and its application in Channel.
Description Check ✅ Passed The PR description is directly relevant to the changeset, providing clear context about SimpleWaitQueue (a non-atomic wait queue for mutex-protected use), its benefits (simpler code, better performance, clearer design), and specific changes made (new implementation, tests, Channel updates). The description accurately reflects what's in the raw summary without being vague, explaining both the what and the why of the changes.

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

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() and sender_queue.pop() are called without holding self.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 nodes

Today 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: read closed under 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

📥 Commits

Reviewing files that changed from the base of the PR and between 050def5 and 2f797c5.

📒 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 solid

Pointer init and head/tail updates are correct; debug guard prevents double-enqueue. No issues.


87-106: Pop correctness

FIFO, head/tail maintenance, and debug in_list handling are correct. Good cleanup of node links.


588-731: Tests cover the core SimpleWaitQueue behaviors

Basic, remove semantics, head/tail removal, and .empty initializer are exercised. Nice coverage.

src/sync/channel.zig (1)

3-3: Switch to SimpleWaitQueue is appropriate here

Channel 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.

@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 (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() (or swapWithEmpty()) to SimpleWaitQueue so close() 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() for SimpleWaitQueue and 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

📥 Commits

Reviewing files that changed from the base of the PR and between 2f797c5 and a33bfac.

📒 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 closed before 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.zig only; no cross-file access to the queue fields. All SimpleWaitQueue operations (push, pop, remove) are consistently guarded by mutex locks—either self.mutex or self.channel.mutex with 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.
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