Repository navigation
Refactor Mutex for thread-safety with tagged pointers - #47
Conversation
This change refactors the Mutex implementation to improve thread-safety using tagged pointer techniques and a mutation spinlock. Changes: - Refactor Mutex to use tagged pointer state encoding in head field: * 0b00 = locked, no waiters * 0b01 = unlocked * ptr (>1) = locked with waiters (head pointer) * ptr | 0b10 = mutation lock held - Add mutation spinlock using fetchOr/fetchXor for thread-safe queue operations - Separate head/tail pointers for clearer queue management - Add comprehensive synchronization comments Benefits: - Thread-safe wait queue modifications via mutation lock - Maintains existing FIFO fairness and O(1) cancellation - Lock-free progress guarantees (spinlock only held briefly) - Clearer correctness reasoning with explicit synchronization All 88 tests passing including Mutex, Semaphore, Condition, Channel, Barrier, ResetEvent, and BroadcastChannel.
WalkthroughReplaced per-primitive owner/wait_queue logic with a pointer-encoded, mutation-bit driven FIFO awaitable queue (ConcurrentAwaitableList); rewired Mutex, Condition, and ResetEvent to use the new executor-aware queue and cancellation-aware yields; changed Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor Task
participant Mutex
participant Queue as ConcurrentAwaitableList
participant Awaitable
participant Executor
rect rgba(225,245,255,0.6)
note right of Mutex: Fast-path tryLock (state CAS)
Task->>Mutex: tryLock()
alt sentinel→locked (CAS succeeds)
Mutex-->>Task: acquired
else CAS fails / locked
Mutex-->>Task: not-acquired
end
end
rect rgba(235,255,235,0.5)
note right of Queue: Slow-path enqueue & suspend (executor-aware)
Task->>Executor: get current executor
Task->>Awaitable: prepare awaitable
Task->>Queue: push(executor, awaitable)
Task-->>Awaitable: yield(.allow_cancel)
Awaitable-->>Task: resume when woken or canceled
end
rect rgba(255,245,230,0.6)
note right of Mutex: Unlock & wake-next
Task->>Mutex: unlock()
alt no waiters
Mutex->>Mutex: clear locked state
else waiters present
Mutex->>Executor: get executor
Mutex->>Queue: pop(executor)
Queue-->>Awaitable: next awaitable
Mutex->>Awaitable: wakeWaiter()
end
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 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: 2
🧹 Nitpick comments (4)
src/sync/Mutex.zig (4)
79-93: Consider adding backoff to mutation lock spinning.The unbounded spin loop (line 80-92) uses only
spinLoopHint()without exponential backoff or periodic yielding. Under high contention, this could waste CPU cycles and degrade performance.Consider adding exponential backoff:
fn acquireMutationLock(self: *Mutex) State { + var spin_count: usize = 0; while (true) { // Try to set mutation bit atomically const old = self.head.fetchOr(0b10, .acquire); const old_state: State = @enumFromInt(old); if (!old_state.hasMutationBit()) { // We got it! old_state is the state before we set the bit return old_state; } // Someone else holds the mutation lock, spin std.atomic.spinLoopHint(); + + // Exponential backoff after initial spins + spin_count += 1; + if (spin_count > 100) { + std.time.sleep(1); + } else if (spin_count > 10) { + for (0..spin_count) |_| std.atomic.spinLoopHint(); + } } }
139-140: Consider removing redundant initialization.Lines 139-140 initialize
awaitable.nextandawaitable.prevto null. IfAwaitableis freshly allocated or already zeroed, this is redundant. However, if the awaitable might be reused, this is necessary.If awaitables are always fresh, consider removing:
- // Initialize awaitable as not in list - awaitable.next = null; - awaitable.prev = null; - while (true) {Otherwise, add a comment explaining why this is needed:
+ // Clear any stale pointers (awaitables may be reused across suspensions) awaitable.next = null; awaitable.prev = null;
335-338: Clarify the safety argument in the comment.The comment (lines 335-338) states that "wakeWaiter() only reads the node", but
wakeWaiter()callsmarkReady()which modifies executor state. The actual safety guarantee is that the awaitable memory remains valid (stack-allocated on the coroutine) and is not concurrently modified.Refine the comment:
// O(1) removal with doubly-linked list - // Note: Even if unlock() is processing this node concurrently, it's safe - // because both operations hold the mutation lock (cannot overlap), and - // wakeWaiter() only reads the node (doesn't modify it). The node remains - // valid memory since it lives on the coroutine's stack. + // Note: This removal is safe even though unlock() may have already dequeued + // this node because: + // 1. Both operations hold the mutation lock, so queue modifications cannot overlap + // 2. The awaitable memory remains valid (stack-allocated on coroutine) + // 3. wakeWaiter() doesn't modify the awaitable's next/prev pointers if (awaitable.prev) |prev| {
64-68: Update alignment comment in fromPtrReplace “// Must be 8-byte aligned” with “// Must be 4-byte aligned” to match the 2-bit tagging mask. Optionally add a compile-time assertion (
comptime std.debug.assert(@alignOf(Awaitable) >= 4);) infromPtror onAwaitableto document this requirement.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/sync/Mutex.zig(4 hunks)
🔇 Additional comments (4)
src/sync/Mutex.zig (4)
105-115: LGTM! Clean parameterless tryLock with correct memory ordering.The removal of the
runtimeparameter simplifies the API, and the memory ordering is well-chosen:.acquireon success to synchronize withunlock's.release,.monotonicon failure since no shared state is accessed.
296-300: LGTM! Clean waiter wake logic.The helper correctly extracts the task and executor from the awaitable and marks the coroutine ready.
330-332: Verify the correctness of the "not in list" check.The check
awaitable.prev == null and head != awaitable(line 330) assumes that an awaitable not at the head with a nullprevpointer is not in the list. However, there's a subtle race:
- Thread A (current coroutine) enqueues awaitable as first waiter (becomes head)
- Thread B (unlock thread) acquires mutation lock, pops head, wakes awaitable
- Thread A (cancellation) acquires mutation lock, sees
prev == nullandhead != awaitableIn this case, returning
falseis correct because the awaitable already inherited the lock andlock()will callunlock()at line 205.The logic appears correct, but please verify this race scenario is handled properly. Consider adding a comment explaining this case:
// Check if we're actually in the list (using prev/next pointers) // If prev is null and we're not head, we're not in the list + // Note: This can happen if we were already dequeued and woken by unlock() + // before we acquired the mutation lock. In that case, we've already + // inherited the lock and should return false. if (awaitable.prev == null and head != awaitable) { return false; // Not in list }
407-410: LGTM! Tests correctly updated for new tryLock signature.The test calls have been properly updated to match the parameterless
tryLock()signature (lines 407, 408, 410).
This commit optimizes the Mutex implementation by reusing CAS failure values instead of performing separate atomic loads, reducing the number of atomic operations in contended scenarios. Key changes: 1. Eliminate redundant loads in lock(): - Reuse CAS failure values instead of separate head.load() calls - Track state across loop iterations to avoid re-reading - Reduces atomic operations from 2+ to 1+ in worst case 2. Strengthen memory ordering for correctness: - Change CAS failure ordering to .acquire where we use the returned value - This synchronizes-with prior releases to see updated state - Applies to both lock() and tryLock() for consistency 3. Optimize releaseMutationLock(): - Return state after clearing mutation bit - Allows callers to continue without additional atomic load - Uses XOR trick: fetchXor returns pre-XOR value, XOR again to get result Benefits: - Fewer atomic operations in hot path - Stronger memory ordering guarantees - Consistent optimization pattern throughout All 88 tests passing including Mutex, Semaphore, Condition, Channel, Barrier, ResetEvent, and BroadcastChannel.
There was a problem hiding this comment.
Actionable comments posted: 1
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/sync/Mutex.zig(4 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-10-15T19:38:44.642Z
Learnt from: lalinsky
PR: lalinsky/zio#47
File: src/sync/Mutex.zig:237-237
Timestamp: 2025-10-15T19:38:44.642Z
Learning: In the `unlock` method of `src/sync/Mutex.zig`, the `runtime` parameter is intentionally retained (marked with `_ = runtime;`) for API consistency and future-proofing, even though it's not currently used in the implementation.
Applied to files:
src/sync/Mutex.zig
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: test (windows-latest)
🔇 Additional comments (6)
src/sync/Mutex.zig (6)
74-100: LGTM! Mutation lock implementation is correct.The acquire/release memory ordering is appropriate:
fetchOr(..., .acquire)synchronizes-with previousfetchXor(..., .release)- The spin-wait pattern is standard for spinlocks
- Returning the old state and checking for race conditions (unlocked/locked_once transitions) properly handles concurrent unlock scenarios
106-116: LGTM! Non-blocking lock acquisition is correct.The use of
.acquireordering on success properly synchronizes-with the previous holder's.releaseinunlock(). The.acquireon failure is harmless (though not strictly needed since we return immediately) and keeps the pattern consistent withlock().
128-216: LGTM! FIFO lock acquisition with proper cancellation handling.The implementation correctly handles:
- Fast-path non-blocking acquire with proper
.acquiresynchronization- Three enqueue cases: unlocked race, first waiter, append to tail
- Memory ordering:
.acquireon CAS failure is correct since the returnedprevvalue is used- Mutation lock protects all queue pointer updates
- Cancellation logic: after successful enqueue,
tryRemoveFromQueuereturningfalsecorrectly indicates lock inheritance, requiring unlock
243-299: LGTM! Proper FIFO unlock with waiter wake-up.The implementation correctly:
- Transitions to unlocked when no waiters with
.releasesynchronization- Uses mutation lock to safely dequeue head and update queue pointers
- Clears dequeued node's pointers before waking (prevents use-after-dequeue)
- Updates head with
.releaseto synchronize-with next acquirer- Preserves tail when multiple waiters remain
Based on learnings: runtime parameter is retained for API consistency.
303-373: LGTM! Helper functions are correct and well-commented.
wakeWaiter(303-307): Simple and correct delegation to executor.
tryRemoveFromQueue(309-373): O(1) removal with proper concurrency handling:
- Mutex lock protects against concurrent unlock operations
- Doubly-linked list manipulation is standard and correct
- Correctly handles edge cases: removing head, tail, or middle nodes
- The comment at lines 342-345 accurately explains the safety guarantees
- Returns
falsewhen not in queue (whether never enqueued or already dequeued), which correctly signals lock inheritance to the cancellation handler
404-428: LGTM! Test correctly updated for parameterlesstryLock().The test properly verifies:
- Initial tryLock succeeds on unlocked mutex
- Subsequent tryLock fails while locked
- tryLock succeeds again after unlock
All three assertions validate expected behavior.
…handling - Add comprehensive memory ordering documentation explaining acquire/release semantics - Fix releaseMutationLock to use fetchAnd with assertion instead of fetchXor - Add in_list debug assertions to catch double-add/remove bugs - Change spin counters from u32 to u4 with wrapping add for auto-yield every 16 spins - Pass executor to acquireMutationLock to enable yielding during lock contention - Fix Mutex unlock race where tryTransition fails but pop returns null due to cancellation
…src/core - Move from src/sync/LockFreeAwaitableQueue.zig to src/core/ConcurrentAwaitableList.zig - Rename type throughout codebase for clarity and consistency - Update all imports in Mutex, Condition, and ResetEvent - Update documentation to use "list" terminology instead of "queue"
Use expectEqual for enum, pointer, and boolean comparisons to provide better error messages when tests fail.
There was a problem hiding this comment.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
src/sync/ResetEvent.zig (2)
122-135: Add acquire fence after resume to honor set()’s happens-before.set() uses a release swap. A waiter that resumes must perform an acquire before returning so prior writes are visible.
if (state == .waiting) { const current = runtime.executor.current_coroutine orelse unreachable; const executor = Executor.fromCoroutine(current); const task = AnyTask.fromCoroutine(current); self.wait_queue.push(executor, &task.awaitable); // Suspend until woken by set() executor.yield(.waiting, .allow_cancel) catch |err| { // On cancellation, remove from queue _ = self.wait_queue.remove(executor, &task.awaitable); return err; }; + // Pair with set()’s .release: ensure visibility of pre-set writes + _ = self.state.load(.acquire); }
168-200: Timed wait: also add acquire fence on successful wake.Ensure the success path observes writes before set()’s release.
executor.timedWaitForReadyWithCallback( timeout_ns, TimeoutContext, &timeout_ctx, struct { fn onTimeout(ctx: *TimeoutContext) bool { // Try to remove from wait queue - if successful, we timed out // If failed, we were already signaled return ctx.wait_queue.remove(ctx.executor, ctx.awaitable); } }.onTimeout, ) catch |err| { // Remove from queue if canceled (timeout already handled by callback) if (err == error.Canceled) { _ = self.wait_queue.remove(executor, &task.awaitable); } return err; }; + // Pair with set()’s .release on the success path + _ = self.state.load(.acquire);
🧹 Nitpick comments (1)
src/runtime.zig (1)
137-154: Document alignment guarantee for tagged pointers.Tagged-pointer users assume lower 2 bits are zero. Make this invariant explicit to prevent future regressions.
You can add after the Awaitable definition:
comptime { std.debug.assert(@alignOf(Awaitable) >= 4); }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
src/core/ConcurrentAwaitableList.zig(1 hunks)src/runtime.zig(7 hunks)src/sync/Condition.zig(6 hunks)src/sync/Mutex.zig(4 hunks)src/sync/ResetEvent.zig(5 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-10-15T19:38:44.642Z
Learnt from: lalinsky
PR: lalinsky/zio#47
File: src/sync/Mutex.zig:237-237
Timestamp: 2025-10-15T19:38:44.642Z
Learning: In the `unlock` method of `src/sync/Mutex.zig`, the `runtime` parameter is intentionally retained (marked with `_ = runtime;`) for API consistency and future-proofing, even though it's not currently used in the implementation.
Applied to files:
src/sync/Mutex.zig
🔇 Additional comments (8)
src/sync/Mutex.zig (1)
138-142: LGTM: clean handoff/wake.Deriving executor from the waiter’s coroutine and markReady is correct and keeps the FIFO handoff tight.
src/sync/ResetEvent.zig (1)
90-96: LGTM: executor-aware popping in set().Using current executor for pop and per-task executor for wake keeps cross-executor correctness.
src/runtime.zig (1)
982-1026: LGTM: yield cancellation mode is well-factored.Pre/post cancellation checks gated by a comptime mode keep hot paths lean and make intent clear.
src/sync/Condition.zig (2)
89-101: LGTM: cancel-safe wait with guaranteed mutex reacquire.push → unlock → yield(.allow_cancel) → on cancel remove + lockNoCancel is correct. This relies on Mutex lock acquisition having acquire semantics (see Mutex/tryTransition fix).
210-217: LGTM: broadcast wakes all waiters via per-task executors.Executor-aware pop loop and per-waiter markReady is consistent with the new queue.
src/core/ConcurrentAwaitableList.zig (3)
145-215: LGTM: first-waiter transition and mutation-lock discipline.
- CAS to pointer|mutation-bit for first waiter, then publish tail, then clear bit → solid.
- Spin/yield with .no_cancel avoids cancellation while contending for the lock.
No issues.
217-278: LGTM: pop releases via store(.release) before waking.Release on head.store followed by wake in caller enables proper handoff once waiters perform an acquire.
280-367: LGTM: O(1) remove under mutation lock.Membership check via prev/head under lock and tail maintenance are correct; debug in_list hygiene helps.
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
src/core/ConcurrentAwaitableList.zig (1)
90-102: Use acq_rel on success to support both lock and unlock transitions.This helper is used for lock acquisition (needs acquire) and unlock (needs release). With success=.release, callers like Mutex.tryLock/lock fast-path do not perform an acquire, breaking the happens-before with the prior unlock.
Change success ordering to .acq_rel:
pub fn tryTransition(self: *ConcurrentAwaitableList, from: State, to: State) bool { std.debug.assert(!from.isPointer() and !to.isPointer()); // .release on success: makes prior modifications visible to threads observing the new state // .acquire on failure: synchronizes-with prior .release to observe current state return self.head.cmpxchgStrong( @intFromEnum(from), @intFromEnum(to), - .release, + .acq_rel, .acquire, ) == null; }
🧹 Nitpick comments (1)
src/core/ConcurrentAwaitableList.zig (1)
37-40: Consider renaming or documentingisPointer()semantics.The function name
isPointer()is misleading—it returnstruefor locked sentinels (0b10, 0b11) which are not actual pointers. The function really checks "not an unlocked sentinel" or "has waiters or mutation lock held."While the current code works correctly because all call sites check
hasMutationBit()afterwards, this implicit precondition makes the API fragile and harder to maintain.Consider one of:
- Rename to
hasWaitersOrLocked()for clarity- Add a doc comment:
/// Returns true if the state is a pointer (with or without mutation bit) or a locked sentinel- Add debug assertions in
getPtr()to enforce that it's only called on unlocked states
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/core/ConcurrentAwaitableList.zig(1 hunks)
🔇 Additional comments (3)
src/core/ConcurrentAwaitableList.zig (3)
145-215: LGTM! Well-handled concurrent push with proper synchronization.The three-path logic (fast-path CAS, spin-wait, lock-and-append) correctly handles concurrent pushes. Memory ordering is appropriate, and the edge case where state transitions to sentinel while waiting for the lock (lines 196-202) is handled correctly.
The implicit lock release via storing a state without the mutation bit (lines 176, 201) is subtle but correct and well-documented.
217-278: LGTM! Correct FIFO pop with proper synchronization.The pop implementation correctly handles both the empty queue case and the removal of the head awaitable. Memory ordering is appropriate, and the implicit lock release via storing states without the mutation bit (lines 266, 272) is correct.
280-367: LGTM! Efficient O(1) removal with doubly-linked list.The remove implementation correctly handles all cases including not-in-list, removing head, and removing tail. The check at lines 320-323 using prev pointers to determine list membership is clever and correct. Memory ordering is appropriate throughout.
Address memory ordering issues identified in code review to ensure correctness on weakly-ordered architectures (ARM, RISC-V). Changes: - ConcurrentAwaitableList.tryTransition: Use .acq_rel on success for bidirectional synchronization (both lock acquisition and unlock) - Mutex.lock: Add acquire fence after yield to synchronize with unlock's release - ResetEvent.wait/timedWait: Add acquire fences after resume to synchronize with set's release swap - Awaitable: Add comptime alignment check for tagged pointer safety All tests passing (90/90).
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
src/runtime.zig (2)
191-199: Add acquire fence after resume to pair with markComplete().
markComplete()storesstate=1with.release. Afteryieldreturns inwaitForComplete, perform an acquire load to establish happens-before before reading results.executor.yield(.waiting, .allow_cancel) catch |err| { // If yield itself was canceled, remove from wait list _ = self.waiting_list.remove(&task.awaitable); return err; }; - // Yield returned successfully, awaitable must be complete + // Pair with markComplete()'s .release + _ = self.state.load(.acquire); + // Yield returned successfully, awaitable must be complete
251-259: Also fence after timed wait resume (success path).Same acquire needed here to synchronize with
markComplete().) catch |err| { // Handle both timeout and cancellation from yield if (err == error.Canceled) { _ = self.waiting_list.remove(&task.awaitable); } return err; }; - // Yield returned successfully, awaitable must be complete + // Pair with markComplete()'s .release + _ = self.state.load(.acquire); + // Yield returned successfully, awaitable must be complete
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
src/core/ConcurrentAwaitableList.zig(1 hunks)src/runtime.zig(8 hunks)src/sync/Mutex.zig(4 hunks)src/sync/ResetEvent.zig(5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- src/core/ConcurrentAwaitableList.zig
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-10-15T19:38:44.642Z
Learnt from: lalinsky
PR: lalinsky/zio#47
File: src/sync/Mutex.zig:237-237
Timestamp: 2025-10-15T19:38:44.642Z
Learning: In the `unlock` method of `src/sync/Mutex.zig`, the `runtime` parameter is intentionally retained (marked with `_ = runtime;`) for API consistency and future-proofing, even though it's not currently used in the implementation.
Applied to files:
src/sync/Mutex.zig
🔇 Additional comments (7)
src/sync/Mutex.zig (4)
89-92: Good: acquire fence after wakeup.The acquire after
yieldcorrectly pairs with unlock’s release inpop()for handoff safety.
123-139: Unlock wake path looks sound.Fast-path transition when no waiters, else pop→wake next waiter; loop handles cancel races. Assuming
pop()does a release prior to wake, this preserves handoff ordering.Please confirm
pop()performs a release before handing the lock to the waiter (documented in ConcurrentAwaitableList).
50-52: No changes needed—tryTransition already ensures acquire semantics on success.The
tryLockfast path is correct.ConcurrentAwaitableList.tryTransitionalready performs.acq_relon successful state transition (line 97–100), which includes acquire ordering to synchronize with the prior owner's release. Option A (preferred) from the review comment is already implemented. No additional acquire load is required.
68-71: Suggested refactor is unnecessary —tryTransitionalready provides acquire semantics on success.The
tryTransitionfunction uses.acq_relmemory ordering on its underlyingcmpxchgStrongoperation (src/core/ConcurrentAwaitableList.zig:100). This ordering provides acquire semantics on success, synchronizing with the prior unlock's release, exactly as documented in the function's memory ordering comment (lines 90-92). The fast-path lock at Mutex.zig:69 already performs the required acquire when the transition succeeds.Likely an incorrect or invalid review comment.
src/runtime.zig (2)
154-160: Alignment guard is appropriate.Compile-time check ensures tagged-pointer invariants. Good safety net.
1483-1484: Runtime.yield: correct delegation to allow_cancel mode.Call site matches new API; cancellation propagates as intended.
src/sync/ResetEvent.zig (1)
90-97: Set path looks correct.Release-store then drain waiters using their own executors; good cross-executor wake semantics.
Eliminates the separate state atomic by encoding the event state directly in the ConcurrentAwaitableList's sentinel states: - sentinel0 = unset (no waiters, event not signaled) - sentinel1 = set (no waiters, event signaled) - pointer = has waiters (event not signaled) Changes: - Extract AwaitableList to src/core/AwaitableList.zig - Add ConcurrentAwaitableList.popAll(target_sentinel) to atomically extract the entire wait queue and transition to target sentinel - Simplify ResetEvent by removing separate state field - Eliminates potential for lost wakeups from race between state and queue This provides a single source of truth for event state and cleaner synchronization guarantees.
Add popOrTransition() method that encapsulates the retry loop for handling cancellation races, eliminating the need for callers to implement their own retry logic. Simplify push(), pop(), and remove() by always acquiring the mutation lock first instead of checking state beforehand. This removes unnecessary optimizations for the empty case and significantly reduces code complexity. Changes: - Add tryTransitionEx() that returns previous state for checking target - Add popOrTransition() that handles cancellation races internally - Simplify Mutex.unlock() from ~20 lines to 6 lines - Simplify ResetEvent.set() to use popOrTransition loop - Simplify push() from ~65 lines to ~27 lines - Simplify pop() from ~55 lines to ~38 lines - Simplify remove() from ~80 lines to ~65 lines Net reduction: 76 lines of code while improving correctness and maintainability.
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/sync/ResetEvent.zig (1)
151-205: Critical: Same lost-wakeup race in timedWait() - add double-check.The same race condition exists in
timedWait()as inwait(). After pushing at line 164, the event could be set, but the waiter has already been added to the queue and will time out incorrectly.Apply this diff:
self.wait_queue.push(executor, &task.awaitable); + + // Double-check state after push to avoid lost wakeup / false timeout + if (self.wait_queue.getState() == is_set) { + _ = self.wait_queue.remove(executor, &task.awaitable); + return; + } const TimeoutContext = struct {
♻️ Duplicate comments (1)
src/sync/ResetEvent.zig (1)
111-140: Critical: Lost-wakeup race in wait() - add double-check after push.A race condition exists between checking
isSet()and pushing to the queue:
- Thread A:
wait()checksgetState()at line 112 → seesunset- Thread B:
set()transitionsunset→is_setviapopOrTransition→ no waiters to wake- Thread A:
push()at line 123 → atomically transitions queue fromis_setback to pointer state- Thread A:
yield()at line 126 → suspends indefinitely (lost wakeup)The queue's atomic
push()doesn't prevent this race because it can transition from theis_setstate back to a pointer state.Apply this diff to add a double-check after push:
self.wait_queue.push(executor, &task.awaitable); + + // Double-check state after push to avoid lost wakeup + // If event was set concurrently, remove ourselves and return + if (self.wait_queue.getState() == is_set) { + _ = self.wait_queue.remove(executor, &task.awaitable); + return; + } // Suspend until woken by set() executor.yield(.waiting, .allow_cancel) catch |err| {Alternative solution: Modify
ConcurrentAwaitableList.push()to refuse pushes when in sentinel1 state and return a boolean indicating success. However, the double-check approach is simpler and aligns with standard condition variable patterns.
🧹 Nitpick comments (1)
src/core/ConcurrentAwaitableList.zig (1)
196-234: Pop correctly removes head and maintains queue invariants.The pop operation:
- Acquires mutation lock and checks for empty queue (lines 197-203)
- Removes head, clears its pointers (lines 205-216)
- If last waiter, transitions to sentinel0; otherwise updates head pointer (lines 218-230)
Both paths implicitly release the mutation lock by storing a state without the mutation bit. The use of
.releaseordering (lines 223, 229) correctly publishes all list updates.The transition to sentinel0 when popping the last waiter is a design choice. This works for Mutex (sentinel0 = locked_once) but means other users need to be aware of this behavior. Consider documenting this in the function comment.
Add a note to the function documentation:
/// Remove and return the awaitable at the front of the list. -/// Returns null if list is in a sentinel state (empty). +/// Returns null if list is in a sentinel state (empty). +/// When removing the last waiter, transitions to sentinel0. +/// Memory ordering: Uses .release when updating head to publish list modifications. pub fn pop(self: *ConcurrentAwaitableList, executor: *Executor) ?*Awaitable {
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
src/core/AwaitableList.zig(1 hunks)src/core/ConcurrentAwaitableList.zig(1 hunks)src/runtime.zig(9 hunks)src/sync/Mutex.zig(4 hunks)src/sync/ResetEvent.zig(7 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-10-15T19:38:44.642Z
Learnt from: lalinsky
PR: lalinsky/zio#47
File: src/sync/Mutex.zig:237-237
Timestamp: 2025-10-15T19:38:44.642Z
Learning: In the `unlock` method of `src/sync/Mutex.zig`, the `runtime` parameter is intentionally retained (marked with `_ = runtime;`) for API consistency and future-proofing, even though it's not currently used in the implementation.
Applied to files:
src/sync/Mutex.zig
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: test (windows-latest)
🔇 Additional comments (13)
src/core/AwaitableList.zig (1)
1-95: LGTM! Clean non-concurrent list implementation.The implementation is correct and handles all edge cases properly:
push()correctly updates head/tail for both empty and non-empty listspop()properly maintains head/tail invariants and clears pointersconcatByMoving()safely handles empty source listsremove()correctly updates neighboring nodes and handles head/tail removalDebug assertions consistently track list membership. No issues found.
src/sync/Mutex.zig (4)
27-42: Well-designed state encoding pattern.The queue-based state encoding eliminates the need for separate owner tracking and provides atomic state transitions:
sentinel1(0b01) = unlocked statesentinel0(0b00) = locked with no waiters- pointer = locked with FIFO wait queue
This design enables lock-free fast paths and proper memory ordering. Clean implementation.
50-52: Simplified tryLock API preserves correctness.The parameterless
tryLock()correctly delegates totryTransition(unlocked, locked_once), which uses.acq_relmemory ordering to ensure proper synchronization on successful acquisition. The simplification removes the unused Runtime parameter while maintaining thread-safety.
64-92: Lock implementation correctly handles fast path, slow path, and cancellation.The fast path via
tryTransitionprovides O(1) lock acquisition when uncontended. The slow path:
- Pushes awaitable to FIFO queue (atomically transitions sentinel→pointer or appends to existing queue)
- Suspends with cancellation support
- On cancellation, removes from queue or releases lock if already inherited
- Includes acquire fence (line 89-91) to synchronize with unlock's release, ensuring visibility of critical section writes
The acquire fence at line 91 correctly pairs with the
.releaseinpopOrTransitioncalled byunlock().
119-131: Unlock correctly wakes next waiter with FIFO fairness.
popOrTransitionatomically:
- Pops next waiter from queue and wakes it, OR
- Transitions from
locked_oncetounlockedif no waitersThe retry loop inside
popOrTransitionhandles cancellation races where waiters remove themselves between the empty check and pop. ThewakeWaiterhelper correctly derives the executor from the waiter's coroutine to mark it ready.src/runtime.zig (2)
879-948: YieldCancelMode design provides elegant compile-time safety.The
YieldCancelModeenum with comptime return type selection is well-designed:
.allow_cancelreturnsCancelable!voidand checks cancellation before/after yield.no_cancelreturnsvoidand never checks cancellation, preventing interruption in critical sectionsThe comptime condition
if (cancel_mode == .allow_cancel)ensures type safety at compile time. The implementation correctly checks and consumes the cancellation flag usingcmpxchgStrongwith.acquiresemantics, respecting shield count. The cancellation checks both before yielding (line 912-918) and after resuming (line 943-947) properly handle all edge cases.
192-192: All yield invocations correctly include.allow_cancelConfirmed that everyexecutor.yieldandself.yieldcall insrc/runtime.zigspecifies.allow_cancel, and theRuntime.yield()wrapper applies.allow_cancelinternally.src/sync/ResetEvent.zig (1)
81-92: Consider race between popOrTransition and concurrent wait() pushes.While
popOrTransitiondrains waiters in a loop, there's a subtle interaction with concurrentwait()calls:
- Thread A:
set()pops last waiter, queue state is nowunset- Thread B:
wait()pushes, transitionsunset→pointer- Thread A:
tryTransition(unset, is_set)succeeds- Thread B's waiter is now in queue, but queue state is
is_setHowever, this scenario is actually safe because:
- Thread B's
wait()will seeis_setin the double-check (once added per my previous comment)- Thread B will remove itself and return immediately
This highlights why the double-check after push is essential. Current implementation without the double-check is broken.
src/core/ConcurrentAwaitableList.zig (5)
1-16: Excellent documentation of tagged pointer scheme.The header clearly explains the state encoding and mutation lock semantics:
- Two sentinel states (0b00, 0b01) for encoding protocol-specific states
- Pointer state (>1) for non-empty wait queues
- Mutation bit (0b10) for short critical sections
This design enables efficient lock-free operations with minimal overhead.
88-119: Memory ordering correctly uses acq_rel for bidirectional synchronization.The
tryTransitionExandtryTransitionfunctions correctly use:
.acq_relon success: synchronizes with both prior releases (unlock paths) and publishes to future acquires (lock paths).acquireon failure: observes current state to enable retry logicThis addresses the past review comment about lock acquisition needing acquire semantics. Well done.
Based on learnings.
121-148: Mutation lock uses proper acquire/release synchronization.The
acquireMutationLock:
- Uses
fetchOrwith.acquireto synchronize with previous lock release (line 133)- Spins with yield on overflow to prevent busy-waiting (lines 142-145)
- Returns state before mutation bit was set
The
releaseMutationLock:
- Uses
fetchAndwith.releaseto publish all modifications (line 158)The yield uses
.no_cancel(line 144), which is correct - can't handle cancellation while holding a spinlock. This demonstrates proper use of the new YieldCancelMode API.
165-192: Push correctly handles first-waiter transition and appends.The push operation:
- Acquires mutation lock (line 174)
- If not a pointer (any sentinel state), initializes queue by setting tail and storing head pointer (lines 177-182)
- Otherwise appends to tail under mutex protection (lines 184-191)
The implementation uses
.releaseon store (line 180) to publish the tail update and awaitable initialization. This is correct.Note:
push()will transition from any sentinel state (including sentinel1) to pointer state. This is a flexible design but means callers must double-check after push if they need to verify the sentinel state wasn't changed by a concurrent operation. See related issues in ResetEvent.wait().
310-335: popOrTransition correctly handles cancellation races.The retry loop handles the race where waiters cancel themselves between the empty check and pop attempt:
- Try to transition from
from_sentineltoto_sentinel(line 316)- If successful or already at target, return null (lines 319-326)
- If queue has waiters, pop one (line 329-331)
- If pop fails (waiter cancelled), retry (line 333)
This pattern is essential for primitives like Mutex where unlock must either wake a waiter OR transition to unlocked state atomically. The loop ensures no waiters are lost.
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
src/runtime.zig (1)
154-160: Move the alignment check out of the struct (invalid container-level comptime block).This
comptimeblock insideAwaitableis not valid Zig container syntax. Place the assertion after the type definition (and optionally document via align).Apply this removal in-place:
- // Compile-time alignment check for tagged pointer support - // ConcurrentAwaitableList uses lower 2 bits for state/mutation lock tagging - comptime { - if (@alignOf(Awaitable) < 4) { - @compileError("Awaitable must be at least 4-byte aligned for tagged pointer operations"); - } - }Add this right after the
Awaitabletype closes:// Compile-time verification that alignment requirement is met (for tagged pointers) comptime { if (@alignOf(Awaitable) < 4) { @compileError("Awaitable must be at least 4-byte aligned for tagged pointer operations"); } }
🧹 Nitpick comments (1)
src/runtime.zig (1)
915-923: Make comptime gating explicit to avoid type-checking unreachable error returns.Wrap cancel checks with a comptime-constant branch so the
.no_cancelinstantiation never type-checks error-return paths. Optionally tighten memory order on successful RMW.- // Check and consume cancellation flag before yielding (unless shielded or no_cancel) - if (cancel_mode == .allow_cancel and current_task.shield_count == 0) { - // cmpxchgStrong returns null on success, current value on failure - if (current_task.awaitable.canceled.cmpxchgStrong(true, false, .acquire, .acquire) == null) { - // CAS succeeded: we consumed true, return canceled - return error.Canceled; - } - } + // Check and consume cancellation flag before yielding (unless shielded) + if (comptime cancel_mode == .allow_cancel) { + if (current_task.shield_count == 0) { + // cmpxchgStrong returns null on success + if (current_task.awaitable.canceled.cmpxchgStrong(true, false, .acq_rel, .acquire) == null) { + return error.Canceled; + } + } + } @@ - // Check again after resuming in case we were canceled while suspended (unless shielded or no_cancel) - if (cancel_mode == .allow_cancel and current_task.shield_count == 0) { - if (current_task.awaitable.canceled.cmpxchgStrong(true, false, .acquire, .acquire) == null) { - return error.Canceled; - } - } + // Check again after resuming in case we were canceled while suspended (unless shielded) + if (comptime cancel_mode == .allow_cancel) { + if (current_task.shield_count == 0) { + if (current_task.awaitable.canceled.cmpxchgStrong(true, false, .acq_rel, .acquire) == null) { + return error.Canceled; + } + } + }Also applies to: 946-952
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/runtime.zig(10 hunks)
🔇 Additional comments (8)
src/runtime.zig (8)
192-197: Coroutine wait path: cancellation and memory ordering look correct.
- Using
.allow_canceland removing from the wait list on cancel is correct.- The acquire load after resume pairs with
markComplete()’s release — good.Also applies to: 198-200
261-263: Timed wait: acquire fence after resume is correct.The acquire load pairs with
markComplete()’s release ensuring proper visibility.
883-909: YieldCancelMode addition and cancellable yield signature LGTM.Return type specialization by comptime param is clear and fits the intended API.
1212-1212: Timed wait callback path: cancellation-aware yield is correct.Using
.allow_cancelwith proper cleanup on error is appropriate.
1279-1279: I/O completion wait: cancellation-aware yield is correct.Loop cancel path for io_uring only is sensible; continuing to wait ensures safety.
1401-1402: Runtime.yield delegates with.allow_cancel— good.No-op outside coroutine, propagates Cancelable inside.
1539-1540: select: yield with.allow_cancelis correct.Matches the cancellation semantics elsewhere; defer cleanup handles waiter removal.
746-748: AwaitableList API verification passed.The
AwaitableListimport correctly providespush,pop, andremovemethods. These are used exclusively via thewaiting_listfield in theAwaitablestruct (line 142), and all method calls match the exported signatures exactly:
push(self: *AwaitableList, awaitable: *Awaitable)✓pop(self: *AwaitableList)✓remove(self: *AwaitableList, awaitable: *Awaitable)✓Other queue fields (
blocking_completions,ready_queue,next_ready_queue) use different types (AwaitableStack,SimpleAwaitableStack), which is appropriate.
Introduces LoopGroup struct to enable sharing backend-specific state across multiple Loop instances, which is needed for IOCP backend where multiple loops should share a single IOCP handle. - Add LoopGroup struct containing Backend.SharedState - Add SharedState to all backends (currently empty structs) - Update Loop to use either external or internal LoopGroup - Update backend init() signatures to accept SharedState pointer - Maintain backward compatibility (loop_group is optional)
Summary
Major refactoring of synchronization primitives to improve thread-safety, reduce memory overhead, and provide more flexible cancellation control.
Key Changes
New
ConcurrentAwaitableListmodule:Mutex refactoring:
0b00= locked with no waiters0b01= unlockedptr= locked with waiters in FIFO queuetryLock()API (no longer requires Runtime parameter)Executor yield enhancements:
YieldCancelModeenum:allow_cancelorno_cancel.no_cancelmode returnsvoidfor use in critical sections (e.g., lock-free algorithms).allow_cancelmode returnsCancelable!voidand checks cancellation flagsUpdated synchronization primitives:
ConcurrentAwaitableListBenefits
Test plan
Summary by CodeRabbit
New Features
Bug Fixes
Refactor
Tests