Repository navigation
Add comprehensive documentation to sync primitives - #45
Conversation
Add detailed module-level and function-level documentation for all sync primitives: Mutex, Condition, Barrier, ResetEvent, Semaphore, Channel, and BroadcastChannel. Each module now includes: - Clear explanations of concepts and behavior - Practical usage examples with task spawning - Documentation for all public functions - Error condition descriptions - Notes on cancellation safety where applicable Also fixes BroadcastChannel.unsubscribe() to shield from cancellation and updates all test code accordingly.
|
Caution Review failedThe pull request is closed. WalkthroughAdds Executor.checkCanceled() and Runtime.checkCanceled(); expands sync exports (RefCounter, SharedPtr); implements or refactors many synchronization primitives (Mutex, Condition, ResetEvent, Semaphore, Barrier, Channel, broadcast_channel) with cancellation/timeouts; adds SharedPtr and ref-counter docs and tests. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant Task as Task
participant Exec as Executor
Note over Task,Exec: Cancellation check after leaving a shielded section
Task->>Exec: endShield()
Task->>Exec: checkCanceled()
Exec-->>Task: ok / error.Canceled
sequenceDiagram
autonumber
participant Task as Task
participant M as Mutex
participant RT as Runtime
Note over Task,M: lock(rt) fast-path then suspend on contention
Task->>M: tryLock()
alt acquired
M-->>Task: locked
else busy
Task->>RT: suspend (enqueue waiter)
RT-->>M: waiter enqueued
M-->>RT: unlock -> transfer ownership
RT-->>Task: wake (lock acquired)
end
Task->>M: unlock()
M-->>RT: transfer to next waiter or set unlocked
sequenceDiagram
autonumber
participant Producer as Producer
participant Channel as Channel[T]
participant Consumer as Consumer
Producer->>Channel: send(item)
alt buffer full
Producer->>Channel: wait(not_full) [cancelable]
end
Consumer->>Channel: receive()
alt buffer empty
Consumer->>Channel: wait(not_empty) [cancelable]
end
Channel-->>Producer: ok / ChannelClosed
Channel-->>Consumer: item / ChannelClosed (drained)
sequenceDiagram
autonumber
participant T1 as Task1
participant TN as TaskN
participant B as Barrier
T1->>B: wait(rt)
TN->>B: wait(rt)
alt last arrives
B-->>T1: wake (leader=true)
B-->>TN: wake (leader=false)
B->>B: generation++ (reset current)
else cancellation/broken
B->>B: broken = true
B-->>T1: error BrokenBarrier / Canceled
B-->>TN: error BrokenBarrier / Canceled
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60–90 minutes Possibly related PRs
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (5)
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 |
Move src/ref_counter.zig to src/sync/ref_counter.zig and document it following the same style as other sync primitives. Export it from both sync.zig and zio.zig for public use. RefCounter is a thread-safe atomic reference counter for shared ownership, useful for shared memory management in server applications. Update runtime.zig to import from the new location.
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 (7)
src/sync/broadcast_channel.zig (2)
93-107: Removing a non-subscribed consumer corrupts the listremove() assumes membership; calling unsubscribe() on an already-unsubscribed Consumer (or never-subscribed) will reset first/last incorrectly if prev/next are null. Guard membership.
Example approach:
- Track membership on the Consumer (e.g., subscribed: bool) set in append(), cleared in remove(), and make unsubscribe() a no-op if not subscribed.
- Alternatively, make remove() return bool and have unsubscribe() ignore false.
pub const Consumer = struct { read_pos: usize = 0, prev: ?*Consumer = null, next: ?*Consumer = null, + subscribed: bool = false, }; @@ fn append(self: *ConsumerList, consumer: *Consumer) void { @@ self.last = consumer; + consumer.subscribed = true; } @@ -fn remove(self: *ConsumerList, consumer: *Consumer) void { +fn remove(self: *ConsumerList, consumer: *Consumer) void { + if (!consumer.subscribed) return; @@ consumer.prev = null; consumer.next = null; + consumer.subscribed = false; }And in unsubscribe():
- self.consumers.remove(consumer); + self.consumers.remove(consumer);(no behavior change needed once remove() guards)
158-164: Avoid usize overflow in lag detection
Use subtraction to compute distance instead of adding two usize values:- if (consumer.read_pos + self.buffer.len < self.write_pos) { + if (self.write_pos - consumer.read_pos > self.buffer.len) {Apply the same change at lines 169–174, 199–204, and 205–212. Consider widening the counters (e.g., to u128) or resetting on wrap for very long-running channels.
src/sync/ResetEvent.zig (2)
114-135: Lost wake race in wait(): enqueue must be followed by a state re-checkBetween cmpxchg to .waiting and yield, set() can swap to .is_set, pop an empty queue, and return before the waiter enqueues, causing the waiter to sleep forever. Re-check state after push and avoid yielding if already set.
Apply this fix:
@@ pub fn wait(self: *ResetEvent, runtime: *Runtime) Cancelable!void { - if (state == .waiting) { + if (state == .waiting) { const current = coroutines.getCurrent() orelse unreachable; const executor = Executor.fromCoroutine(current); const task = AnyTask.fromCoroutine(current); self.wait_queue.push(&task.awaitable); + // Avoid lost wake: if set() raced, do not sleep. + if (self.state.load(.acquire) == .is_set) { + // If remove fails, we were already signaled. + _ = self.wait_queue.remove(&task.awaitable); + return; + } + // Suspend until woken by set() executor.yield(.waiting) catch |err| { // On cancellation, remove from queue _ = self.wait_queue.remove(&task.awaitable); return err; }; }
149-198: Same lost wake in timedWait(): add post-enqueue state re-checktimedWait enqueues then waits; set() racing just before enqueue leads to a sleeper that never wakes. Re-check state and skip waiting if already set.
@@ pub fn timedWait(self: *ResetEvent, runtime: *Runtime, timeout_ns: u64) error{ Timeout, Canceled }!void { self.wait_queue.push(&task.awaitable); + // Avoid lost wake: if set() raced, do not wait. + if (self.state.load(.acquire) == .is_set) { + _ = self.wait_queue.remove(&task.awaitable); + return; + } + const TimeoutContext = struct {src/sync/Mutex.zig (1)
95-111: Wake the waiter via its own executor, not the current oneunlock() builds the executor from current instead of the woken task, unlike Condition/ResetEvent. This can misroute scheduling if executors are per-task. Align with others.
pub fn unlock(self: *Mutex, runtime: *Runtime) void { _ = runtime; const current = coroutines.getCurrent() orelse unreachable; - const executor = Executor.fromCoroutine(current); std.debug.assert(self.owner.load(.monotonic) == current); // Check if there are waiters if (self.wait_queue.pop()) |awaitable| { const task = AnyTask.fromAwaitable(awaitable); // Transfer ownership directly to next waiter self.owner.store(&task.coro, .release); - // Wake them up (they already own the lock) - executor.markReady(&task.coro); + // Wake them up (they already own the lock) + const exec = Executor.fromCoroutine(&task.coro); + exec.markReady(&task.coro); } else { // No waiters, release the lock completely self.owner.store(null, .release); } }src/sync/Condition.zig (1)
85-107: Guarantee mutex is held on return (success path bug)Doc promises the mutex is held on return, even if cancellation occurs during reacquire. Current success path uses
try mutex.lock(...), which can return error and exit without holding the mutex, violating the invariant and breaking callers (e.g., Semaphore.wait).Apply this fix:
- // Re-acquire mutex after waking - try mutex.lock(runtime); + // Re-acquire mutex after waking — retry until held, ignoring cancellation + while (true) { + mutex.lock(runtime) catch continue; + break; + }This mirrors your timedWait reacquire loop.
src/sync/Barrier.zig (1)
51-58: Barrier type is missing its struct container (won’t compile).Fields are declared at file scope and
@This()is used outside a container.init/waitare also outside a struct. Wrap these in apub const Barrier = struct { ... };and use a properSelfalias.Apply this diff:
@@ -const Mutex = @import("Mutex.zig"); -const Condition = @import("Condition.zig"); -mutex: Mutex = Mutex.init, -cond: Condition = Condition.init, -count: usize, -current: usize = 0, -generation: usize = 0, -broken: bool = false, - -const Barrier = @This(); +const Mutex = @import("Mutex.zig"); +const Condition = @import("Condition.zig"); + +pub const Barrier = struct { + mutex: Mutex = Mutex.init, + cond: Condition = Condition.init, + count: usize, + current: usize = 0, + generation: usize = 0, + broken: bool = false, + + const Self = @This(); @@ -pub fn init(count: usize) Barrier { +pub fn init(count: usize) Self { std.debug.assert(count > 0); return .{ .count = count }; } @@ -pub fn wait(self: *Barrier, runtime: *Runtime) (Cancelable || error{BrokenBarrier})!bool { +pub fn wait(self: *Self, runtime: *Runtime) (Cancelable || error{BrokenBarrier})!bool { @@ - } -} + } +};Also applies to: 60-66, 87-124
🧹 Nitpick comments (4)
src/sync/Mutex.zig (1)
59-61: Typo: error type spellingDocs say error.Cancelled, code uses error.Canceled. Prefer consistent single-l spelling to match error type.
src/sync/Semaphore.zig (1)
62-79: Depends on Condition.wait reacquiring the mutexYour correctness here relies on Condition.wait guaranteeing the mutex is held on return (success or error). With the current Condition.wait bug (success path uses try), unlock assertions may trip. After fixing Condition.wait, this looks good.
src/sync/channel.zig (2)
200-230: Immediate close drops buffered items without cleanup hooks.If T owns resources (allocations/FDs),
immediate = truediscards items without cleanup. Consider adding aclearWithhelper (or an overload ofclosethat accepts adropcallback) to release resources for buffered items before zeroing the queue. Also mention this caveat in docs.
83-90: Make error sets explicit for API stability (optional).To document/lock API, consider explicit error sets, e.g.:
receive: (Cancelable || error{ChannelClosed})!TtryReceive: (Cancelable || error{ChannelEmpty, ChannelClosed})!Tsend: (Cancelable || error{ChannelClosed})!voidtrySend: (Cancelable || error{ChannelFull, ChannelClosed})!voidThis clarifies behavior and avoids error-set widening across changes.
Also applies to: 115-122, 174-181
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (7)
src/sync/Barrier.zig(2 hunks)src/sync/Condition.zig(5 hunks)src/sync/Mutex.zig(3 hunks)src/sync/ResetEvent.zig(4 hunks)src/sync/Semaphore.zig(3 hunks)src/sync/broadcast_channel.zig(15 hunks)src/sync/channel.zig(6 hunks)
🔇 Additional comments (3)
src/sync/broadcast_channel.zig (1)
130-142: Unsubscribe shielding and non-throwing API LGTMShielding cleanup from cancellation is correct; void return simplifies call sites. Tests reflect this.
src/sync/Condition.zig (1)
121-188: Timed wait reacquire already robust — consistency notetimedWait correctly reacquires the mutex in a loop and prioritizes cancellation over timeout. Once wait() is fixed similarly, both APIs will align.
src/sync/channel.zig (1)
83-113: Core channel ops look correct.FIFO ring buffer, signaling, and cancellation handling are solid.
Also applies to: 142-172
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 (3)
src/sync/ResetEvent.zig (2)
114-138: Fix race: waiter can miss set() between state transition and queue pushIf set() swaps to is_set after cmpxchg(.unset→.waiting) but before the waiter pushes to wait_queue, set() will pop no one; the waiter then enqueues and yields, potentially blocking until a future set. Re-check after enqueue and skip yielding if already set.
Apply this diff:
@@ - // If we're now in waiting state, add to queue and block - if (state == .waiting) { - const current = coroutines.getCurrent() orelse unreachable; - const executor = Executor.fromCoroutine(current); - const task = AnyTask.fromCoroutine(current); - self.wait_queue.push(&task.awaitable); - - // Suspend until woken by set() - executor.yield(.waiting) catch |err| { - // On cancellation, remove from queue - _ = self.wait_queue.remove(&task.awaitable); - return err; - }; - } - - // If state is is_set, we return immediately (event already set) - std.debug.assert(state == .is_set or state == .waiting); + // If we're now in waiting state, add to queue and block + if (state == .waiting) { + const current = coroutines.getCurrent() orelse unreachable; + const executor = Executor.fromCoroutine(current); + const task = AnyTask.fromCoroutine(current); + self.wait_queue.push(&task.awaitable); + + // Re-check after enqueuing to avoid race with set() + if (self.state.load(.acquire) == .is_set) { + // Best-effort remove; if it fails, we were already signaled + _ = self.wait_queue.remove(&task.awaitable); + return; + } + + // Suspend until woken by set() + executor.yield(.waiting) catch |err| { + // On cancellation, remove from queue + _ = self.wait_queue.remove(&task.awaitable); + return err; + }; + } + + // Event should be set here, or we yielded above + std.debug.assert(self.state.load(.acquire) == .is_set);
163-198: Apply the same enqueue-after-check race fix to timedWaitRe-check state after pushing; if already set, remove and return instead of arming the timer.
Apply this diff:
@@ - self.wait_queue.push(&task.awaitable); + self.wait_queue.push(&task.awaitable); + + // Re-check after enqueuing to avoid race with set() + if (self.state.load(.acquire) == .is_set) { + _ = self.wait_queue.remove(&task.awaitable); + return; + } @@ executor.timedWaitForReadyWithCallback(src/sync/Condition.zig (1)
93-107: Fix invariant: always hold the mutex when wait() returns, even if cancellation happens during re‑acquireCurrently, after a successful wake,
try mutex.lock(rt)can itself be canceled, causing wait() to return error.Canceled without holding the mutex, violating the documented invariant. Mirror the timedWait() approach: re‑acquire in a loop, record cancellation, and return error.Canceled only after the mutex is held.- // Re-acquire mutex after waking - try mutex.lock(runtime); + // Re-acquire mutex before returning; ignore cancellation while locking + var was_canceled = false; + while (true) { + mutex.lock(runtime) catch { + was_canceled = true; + continue; + }; + break; + } + if (was_canceled) return error.Canceled;
🧹 Nitpick comments (10)
src/sync/ResetEvent.zig (1)
79-96: Optional: drop the early-return in set()The pre-check can introduce a TOCTOU with a concurrent reset and isn't needed. Always swapping to is_set is idempotent and simpler.
Apply this diff:
- // Quick check if already set to avoid unnecessary atomic operations - if (self.state.load(.monotonic) == .is_set) { - return; - } - - // Atomically set to is_set and get the previous state - const prev_state = self.state.swap(.is_set, .release); + // Atomically set to is_set and get the previous state (idempotent) + const prev_state = self.state.swap(.is_set, .release);src/sync/ref_counter.zig (2)
60-66: Constrain T to integer at compile timePrevents accidental instantiation with non-integer types.
Apply this diff:
pub fn RefCounter(comptime T: type) type { - return struct { + comptime { + if (@typeInfo(T) != .Int) { + @compileError("RefCounter expects an integer type parameter"); + } + } + return struct {
79-81: Guard against overflow on incr()Add a debug assertion to prevent wraparound.
Apply this diff:
pub fn incr(self: *Self) void { - const prev_ref_count = self.refs.fetchAdd(1, .monotonic); + const prev_ref_count = self.refs.fetchAdd(1, .monotonic); + std.debug.assert(prev_ref_count < std.math.maxInt(T)); std.debug.assert(prev_ref_count > 0); }src/runtime.zig (1)
15-15: Prefer importing RefCounter via the public sync module re‑exportAvoid coupling to the internal file path; import through sync.zig for stability.
-const RefCounter = @import("sync/ref_counter.zig").RefCounter; +const RefCounter = @import("sync.zig").RefCounter;src/sync/broadcast_channel.zig (1)
130-142: Unsubscribe is now cancellation‑shielded (good). Guard against double unsubscribe to avoid list corruptionIf unsubscribe is called twice for the same Consumer, remove() will corrupt the list. Add an idempotency/membership guard before removal.
pub fn unsubscribe(self: *Self, runtime: *Runtime, consumer: *Consumer) void { // Shield unsubscribe operation from cancellation runtime.beginShield(); defer runtime.endShield(); self.mutex.lock(runtime) catch unreachable; defer self.mutex.unlock(runtime); - self.consumers.remove(consumer); + // Idempotency: skip if the consumer is not in the list + var cur = self.consumers.first; + var in_list = false; + while (cur) |c| { + if (c == consumer) { in_list = true; break; } + cur = c.next; + } + if (!in_list) return; + self.consumers.remove(consumer); }src/sync/channel.zig (5)
69-75: Document cancellation on isEmpty().Since lock(rt) can return error.Canceled, mention it in docs for clarity.
- /// Checks if the channel is empty. + /// Checks if the channel is empty. + /// May return `error.Canceled` if the task is canceled while acquiring the lock.
76-82: Document cancellation on isFull().Same rationale as isEmpty().
- /// Checks if the channel is full. + /// Checks if the channel is full. + /// May return `error.Canceled` if the task is canceled while acquiring the lock.
200-231: Make close() idempotent and clarify immediate-drop behavior.
- Optional: early-return if already closed to avoid surprising “second-call clears buffer” behavior.
- Doc: note that buffered items are dropped without deinit on immediate close.
pub fn close(self: *Self, rt: *Runtime, immediate: bool) void { // Shield close operation from cancellation rt.beginShield(); defer rt.endShield(); self.mutex.lock(rt) catch unreachable; defer self.mutex.unlock(rt); - self.closed = true; + if (self.closed) { + // Already closed; nothing to do (idempotent) + return; + } + self.closed = true; if (immediate) { // Clear the buffer self.head = 0; self.tail = 0; self.count = 0; }Additionally, consider updating the doc above to:
- /// If `immediate` is true, clears all buffered items immediately. This causes - /// receivers to get `error.ChannelClosed` right away instead of draining. + /// If `immediate` is true, clears all buffered items immediately (they are dropped + /// without running any user-defined deinit). This causes receivers to get + /// `error.ChannelClosed` right away instead of draining.
17-41: Example loop style: consider a catch/break pattern for portability.Depending on Zig version,
while (ch.receive(rt)) |value| ... else |err| ...may not compile. A safer pattern:while (true) { const value = ch.receive(rt) catch |err| switch (err) { error.ChannelClosed => break, else => return err, }; std.debug.print("Received: {}\n", .{value}); }
47-61: Optional API additions: len() and capacity().Handy introspection without forcing callers to interpret emptiness/fullness.
Add alongside existing methods:
pub fn len(self: *Self, rt: *Runtime) !usize { try self.mutex.lock(rt); defer self.mutex.unlock(rt); return self.count; } pub fn capacity(self: *Self) usize { return self.buffer.len; }Also applies to: 115-122, 142-148, 174-181, 200-210
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (11)
src/runtime.zig(1 hunks)src/sync.zig(2 hunks)src/sync/Barrier.zig(2 hunks)src/sync/Condition.zig(5 hunks)src/sync/Mutex.zig(3 hunks)src/sync/ResetEvent.zig(4 hunks)src/sync/Semaphore.zig(3 hunks)src/sync/broadcast_channel.zig(15 hunks)src/sync/channel.zig(6 hunks)src/sync/ref_counter.zig(3 hunks)src/zio.zig(1 hunks)
🔇 Additional comments (12)
src/sync/Semaphore.zig (1)
61-79: Semaphore wait/timedWait/post look solidMutex-guarded state, correct loop predicate, cancellation handling, timeout math, and shielded post are all appropriate. Tests cover key paths.
Also applies to: 91-121, 128-138
src/sync/Barrier.zig (1)
87-124: Barrier wait/broken semantics are correctGeneration tracking, leader return, cancel → broken + broadcast behavior all look correct and race-free under the mutex.
src/sync.zig (1)
11-12: RefCounter re-export looks goodPublic surface and test re-export are consistent with existing pattern.
Also applies to: 22-23
src/zio.zig (1)
33-33: LGTM: RefCounter re‑exportConsistent with the sync surface consolidation. No concerns.
src/sync/broadcast_channel.zig (1)
279-279: LGTM: defer unsubscribe after subscribeSwitching to a void, cancellation‑shielded unsubscribe pairs well with defer and simplifies call sites. Consistent across tests.
Also applies to: 323-323, 367-367, 409-409, 453-453, 556-556, 597-597, 642-642
src/sync/Condition.zig (1)
121-187: LGTM: timedWait cancellation/timeout semantics and re‑acquire loopThe timeout callback removal, cancellation priority, and re‑acquire loop are correct and robust.
src/sync/Mutex.zig (1)
61-111: LGTM: cooperative lock with cancellation and ownership transfer
- Fast‑path tryLock + queue/yield slow‑path is sound.
- On cancellation, removing from queue or dropping inherited lock via unlock() avoids stuck ownership.
- unlock() transfers ownership before waking the waiter, matching the post‑wake assert.
No changes requested.
src/sync/channel.zig (5)
62-68: Init looks good.Capacity > 0 asserted and buffer-based init is clear.
83-113: Receive path: state machine and wakeups look correct.Loop on empty+!closed, recheck after wait, signal not_full on consume. Good.
115-141: tryReceive semantics LGTM.Correct ChannelEmpty vs ChannelClosed distinction; signals not_full on success.
142-173: send() blocking semantics LGTM.Closed checks before and after waits; not_empty signal on enqueue is correct.
174-199: trySend semantics LGTM.Immediate errors for full/closed; not_empty signal on enqueue is correct.
Condition.wait() and timedWait() promised to always hold the mutex on return, even during cancellation. The success path used try mutex.lock() which could fail and exit without holding the mutex, violating this invariant and breaking callers (e.g., Semaphore.wait using defer unlock). Solution: - Add Mutex.lockNoCancel() that uses shield to guarantee lock acquisition - Add Runtime.checkCanceled() to detect cancellation after shielded ops - Update Condition.wait/timedWait to use lockNoCancel + checkCanceled - Simplify Semaphore.post, Channel.close, BroadcastChannel.unsubscribe The new lockNoCancel() helper is cleaner than manual shield + catch unreachable, and checkCanceled() allows flexible cancellation handling.
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/broadcast_channel.zig (1)
93-107: Fix unsafe ConsumerList.remove and guard subscribe/unsubscribe against misuse/double callsremove() assumes membership. Calling unsubscribe() twice or with a non-member consumer corrupts the list (may null-out first/last). Guard membership and make unsubscribe idempotent.
Apply this diff:
@@ const ConsumerList = struct { first: ?*Consumer = null, last: ?*Consumer = null, @@ fn remove(self: *ConsumerList, consumer: *Consumer) void { + // Defensive: only remove if currently linked + if (consumer.prev == null and consumer.next == null and self.first != consumer) { + return; // not a member; no-op + } if (consumer.prev) |prev| { prev.next = consumer.next; } else { self.first = consumer.next; } if (consumer.next) |next| { next.prev = consumer.prev; } else { self.last = consumer.prev; } consumer.prev = null; consumer.next = null; } + + fn contains(self: *ConsumerList, consumer: *Consumer) bool { + return consumer.prev != null or consumer.next != null or self.first == consumer; + } }; @@ - pub fn subscribe(self: *Self, runtime: *Runtime, consumer: *Consumer) !void { + pub fn subscribe(self: *Self, runtime: *Runtime, consumer: *Consumer) !void { try self.mutex.lock(runtime); defer self.mutex.unlock(runtime); + // Prevent double-subscribe; idempotent no-op + if (self.consumers.contains(consumer)) return; consumer.read_pos = self.write_pos; self.consumers.append(consumer); } @@ - pub fn unsubscribe(self: *Self, runtime: *Runtime, consumer: *Consumer) void { + pub fn unsubscribe(self: *Self, runtime: *Runtime, consumer: *Consumer) void { self.mutex.lockNoCancel(runtime); defer self.mutex.unlock(runtime); - self.consumers.remove(consumer); + if (self.consumers.contains(consumer)) { + self.consumers.remove(consumer); + } }Also applies to: 116-128, 133-138
🧹 Nitpick comments (3)
src/sync/broadcast_channel.zig (2)
154-160: Make lag detection overflow-safeconsumer.read_pos + buffer.len < write_pos risks usize overflow in debug and misclassification after long runs. Compute difference instead.
Apply this diff:
- if (consumer.read_pos + self.buffer.len < self.write_pos) { + const behind = std.math.sub(usize, self.write_pos, consumer.read_pos) catch 0; + if (behind > self.buffer.len) { // Skip to the oldest available message consumer.read_pos = self.write_pos - self.buffer.len; return error.Lagged; } @@ - if (consumer.read_pos + self.buffer.len < self.write_pos) { + const behind2 = std.math.sub(usize, self.write_pos, consumer.read_pos) catch 0; + if (behind2 > self.buffer.len) { consumer.read_pos = self.write_pos - self.buffer.len; return error.Lagged; }And in tryReceive:
- if (consumer.read_pos + self.buffer.len < self.write_pos) { + const behind = std.math.sub(usize, self.write_pos, consumer.read_pos) catch 0; + if (behind > self.buffer.len) { consumer.read_pos = self.write_pos - self.buffer.len; return error.Lagged; }Also applies to: 166-170, 195-199
242-250: Consider shielding close() to guarantee completionClosing while cancelable can leave the channel open if cancellation happens mid-operation. Shield it like unsubscribe/post.
Apply this diff to make close robust without changing the signature:
- pub fn close(self: *Self, runtime: *Runtime) !void { - try self.mutex.lock(runtime); + pub fn close(self: *Self, runtime: *Runtime) !void { + self.mutex.lockNoCancel(runtime); defer self.mutex.unlock(runtime); self.closed = true; // Wake all waiting consumers so they can see the channel is closed self.not_empty.broadcast(runtime); }src/sync/Mutex.zig (1)
111-128: Use the target task’s executor when waking in unlock()Currently derives executor from current coroutine; use the woken task’s executor for consistency (matches Condition.signal) and future multi-executor safety.
Apply this diff:
pub fn unlock(self: *Mutex, runtime: *Runtime) void { _ = runtime; const current = coroutines.getCurrent() orelse unreachable; - const executor = Executor.fromCoroutine(current); std.debug.assert(self.owner.load(.monotonic) == current); // Check if there are waiters if (self.wait_queue.pop()) |awaitable| { const task = AnyTask.fromAwaitable(awaitable); // Transfer ownership directly to next waiter self.owner.store(&task.coro, .release); // Wake them up (they already own the lock) - executor.markReady(&task.coro); + const exec = Executor.fromCoroutine(&task.coro); + exec.markReady(&task.coro); } else { // No waiters, release the lock completely self.owner.store(null, .release); } }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (7)
src/runtime.zig(3 hunks)src/sync.zig(2 hunks)src/sync/Condition.zig(5 hunks)src/sync/Mutex.zig(3 hunks)src/sync/Semaphore.zig(3 hunks)src/sync/broadcast_channel.zig(15 hunks)src/sync/channel.zig(6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- src/sync.zig
🔇 Additional comments (19)
src/runtime.zig (3)
15-15: Import path update looks correctRefCounter re-import from sync/ref_counter.zig aligns with new exports. No issues.
960-971: Cancellation check API is sound and consumption semantics are clearAtomically consuming the cancellation flag with acquire ordering is correct and matches yield() behavior. Good documentation and intended post-shield usage.
1437-1445: Runtime.checkCanceled passthrough is correctNo-op outside coroutine and proper delegation to Executor.checkCanceled. Good.
src/sync/broadcast_channel.zig (1)
1-50: Docs are thorough and clearGreat overview and example. Nice alignment with zio runtime semantics.
src/sync/Condition.zig (2)
84-105: wait(): cancellation and mutex reacquire semantics look correctQueue before unlock, handle cancellation by dequeue+reacquire (no‑cancel), and propagate post‑lock cancellation via checkCanceled(). Solid.
119-166: timedWait(): correct priority to cancellation and invariant preservationTimeout context + dequeue on timeout, reacquire with no‑cancel, and favor Canceled over Timeout. Looks good.
src/sync/Semaphore.zig (3)
61-79: wait(): correct cancellation handling and signalingLoop + cond.wait with wake-on-permit race is good. Decrement and signal when permits remain is correct.
91-120: timedWait(): timeout and cancellation paths are correctLocal timeout calculation and proper signaling on cancel look good.
129-134: post(): cancellation-shielded critical section is appropriateEnsures permits aren’t lost. Good alignment with Mutex.lockNoCancel.
src/sync/Mutex.zig (1)
97-101: lockNoCancel(): correct shielding patternbeginShield/endShield around lock() is appropriate; post-acquire cancellation can be checked by callers via runtime.checkCanceled().
src/sync/channel.zig (9)
1-41: Excellent comprehensive documentation.The module documentation clearly explains the channel's behavior, including backpressure, FIFO ordering, blocking semantics, and close/drain behavior. The example is practical and demonstrates proper usage.
47-60: LGTM! Well-structured ring buffer with proper synchronization.The channel structure correctly implements a ring buffer with separate head/tail pointers and a count field to disambiguate full vs empty states. The use of a mutex with two condition variables (
not_empty,not_full) follows the standard monitor pattern for producer-consumer synchronization.
62-81: LGTM! Proper initialization and state query methods.The initialization includes a defensive assertion for non-zero capacity. The
isEmptyandisFullmethods correctly lock the mutex for atomic state queries, though callers should be aware that the results may become stale by the time they're used—this is inherent to any query method in a concurrent system.
83-113: LGTM! Correct receive implementation with proper drain semantics.The receive logic correctly:
- Blocks while empty and not closed, allowing graceful draining after close
- Returns
error.ChannelClosedonly when both closed and empty- Updates the ring buffer head pointer with proper modulo arithmetic
- Signals waiting senders via
not_full- Handles cancellation correctly (defer ensures unlock)
115-140: LGTM! Correct non-blocking receive implementation.The
tryReceivemethod properly implements non-blocking semantics, returning appropriate errors (ChannelEmptyorChannelClosed) when no item is available, and signalingnot_fullwhen an item is successfully retrieved.
142-172: LGTM! Correct send implementation with proper close handling.The send logic correctly:
- Checks if closed before attempting to send
- Blocks while full with proper condition variable usage
- Importantly re-checks the closed flag after waking (line 160-162), which is essential since the channel could be closed while the task is waiting
- Updates the ring buffer tail pointer correctly
- Signals waiting receivers via
not_empty
174-198: LGTM! Correct non-blocking send implementation.The
trySendmethod properly implements non-blocking semantics with appropriate error codes for closed and full states, and correctly signalsnot_emptywhen an item is successfully sent.
200-226: LGTM! Correct close implementation with cancellation safety.The close method is properly implemented:
- Uses
lockNoCancel(line 211) to shield from cancellation, ensuring the close operation completes reliably as documented- Supports both graceful (drain buffered items) and immediate (clear buffer) close semantics
- Broadcasts to both condition variables to wake all waiting tasks, allowing them to observe the closed state
230-544: LGTM! Comprehensive test coverage.The test suite thoroughly validates:
- Basic send/receive operations
- Non-blocking try operations and their error conditions
- Blocking behavior when empty or full
- Multiple concurrent producers and consumers
- Both graceful and immediate close semantics
- Sending on a closed channel
- Ring buffer wrap-around behavior
The tests demonstrate proper usage patterns and verify correctness under various scenarios.
| /// Creates a new condition variable. | ||
| pub const init: Condition = .{}; | ||
|
|
||
| /// Atomically releases the mutex and waits for a signal. | ||
| /// | ||
| /// This function must be called while holding the mutex. It will: | ||
| /// 1. Add the current task to the wait queue | ||
| /// 2. Release the mutex | ||
| /// 3. Suspend until signaled by `signal()` or `broadcast()` | ||
| /// 4. Reacquire the mutex before returning | ||
| /// | ||
| /// This function should typically be called in a loop that checks the condition: | ||
| /// ```zig | ||
| /// try mutex.lock(rt); | ||
| /// defer mutex.unlock(rt); | ||
| /// while (!condition_is_true) { | ||
| /// try condition.wait(rt, &mutex); | ||
| /// } | ||
| /// ``` | ||
| /// | ||
| /// Returns `error.Cancelled` if the task is cancelled while waiting. The mutex | ||
| /// will still be held when returning with an error. | ||
| pub fn wait(self: *Condition, runtime: *Runtime, mutex: *Mutex) Cancelable!void { |
There was a problem hiding this comment.
Doc typos: use “Canceled” consistently
Comments say error.Cancelled; the code uses error.Canceled. Please fix spelling to avoid confusion.
Also applies to: 107-119
🤖 Prompt for AI Agents
In src/sync/Condition.zig around lines 62-84 (and also apply the same change at
lines 107-119), the doc comment uses the British spelling `error.Cancelled` but
the code uses `error.Canceled`; update the comments to use `error.Canceled`
consistently (match the actual error identifier used in code) so all occurrences
in these comment blocks reflect the correct American spelling `Canceled`.
Resolved conflicts: - Updated Mutex.tryLock() to use runtime parameter - Kept checkCanceled() method in Executor and Runtime - Fixed Runtime.checkCanceled() to use executor.current_coroutine
* Handle Async notifications before submission If an Async completion is notified before being submitted to the loop, it now completes immediately upon submission instead of waiting for another notify() call. Changes: - Make Async.loop optional to allow notify() before submission - Add checkAndSetAsyncResult() helper to deduplicate pending check logic - Check for pending state in loop.add() and complete immediately if set - Clear loop reference when Async completes * Refactor buffer API to store iovecs directly Changes ReadBuf and WriteBuf to hold iovec arrays directly instead of wrapping individual iovecs. This simplifies the API by: - Removing intermediate buffer wrapper arrays - Eliminating the toIovecs() conversion step - Making storage management more explicit - Reducing allocations and improving clarity Breaking changes: - ReadBuf.fromSlice() and WriteBuf.fromSlice() now require storage parameter - ReadBuf.fromSlices() now returns ReadBuf instead of []ReadBuf - Completion types now take ReadBuf/WriteBuf instead of slices - Field names changed from plural (buffers) to singular (buffer)
Summary
This PR adds comprehensive documentation to all synchronization primitives in the
src/sync/directory.Documentation added for:
Changes:
BroadcastChannel.unsubscribe()to shield from cancellationAll tests pass.
Summary by CodeRabbit
New Features
Refactor
Documentation
Tests