Repository navigation
Add Barrier synchronization primitive and refactor BroadcastChannel tests - #40
Conversation
…ests
This commit introduces a new Barrier primitive for coordinating multiple
coroutines at a synchronization point, and refactors the BroadcastChannel
tests to use it instead of ResetEvent and atomic counters.
Changes:
- Add Barrier struct with generation-based synchronization
- Barrier.wait() returns true for the last arrival ("leader")
- Barrier automatically resets for multiple synchronization cycles
- Add comprehensive tests for Barrier functionality
- Refactor BroadcastChannel tests to use Barrier for cleaner coordination
WalkthroughReplaces in-file synchronization implementations with dedicated modules and public re-exports from Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant C as Coroutine
participant M as Mutex
participant CV as Condition
participant R as Runtime
participant Q as Queue / Channel
Note over C,M: Lock fast-path or slow-path via runtime await
C->>M: tryLock()
alt fast acquire
M-->>C: locked
else slow-path
C->>R: enqueue waiter & yield
R-->>C: resume when ready
C->>M: owned after resume
end
Note over C,CV: Wait with mutex handoff
C->>CV: wait(runtime, &mutex)
CV->>M: unlock (handoff)
C->>R: yield
R-->>C: markReady (signal/broadcast)
C->>M: re-lock on wake
Note over C,Q: Producer/consumer via Queue/BroadcastChannel
C->>Q: put/send (may block if full)
alt blocked
C->>R: enqueue waiter & yield
R-->>C: resumed on not_full
end
C->>Q: get/receive (may block if empty)
alt blocked
C->>R: enqueue waiter & yield
R-->>C: resumed on not_empty
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: 0
🧹 Nitpick comments (2)
src/sync.zig (2)
1218-1264: Barrier: tighten arrival condition and add bounds assertUse exact equality to avoid masking misuse and assert the bound to catch programming errors early.
@@ pub fn wait(self: *Barrier, runtime: *Runtime) bool { self.mutex.lock(runtime); defer self.mutex.unlock(runtime); const local_gen = self.generation; self.current += 1; + std.debug.assert(self.current <= self.count); - if (self.current >= self.count) { + if (self.current == self.count) { // Last one to arrive - release everyone self.current = 0; self.generation += 1; self.cond.broadcast(runtime); return true; } else { // Wait for the barrier to be released while (self.generation == local_gen) { self.cond.wait(runtime, &self.mutex); } return false; } } }
1998-2016: Simplify error handling to clearly assert error.Closed in waiterUse catch to handle the error union directly and assert expectations.
- fn waiter(rt: *Runtime, ch: *BroadcastChannel(u32), consumer: *BroadcastChannel(u32).Consumer, got_closed: *bool, b: *Barrier) !void { + fn waiter(rt: *Runtime, ch: *BroadcastChannel(u32), consumer: *BroadcastChannel(u32).Consumer, got_closed: *bool, b: *Barrier) !void { ch.subscribe(rt, consumer); defer ch.unsubscribe(rt, consumer); _ = b.wait(rt); // Signal that we're subscribed and about to wait - // Wait for message (channel is empty, so will block) - const err = ch.receive(rt, consumer); - if (err) |_| { - // Shouldn't get a value - } else |e| { - if (e == error.Closed) { - got_closed.* = true; - } - } + // Wait for message (channel is empty, so will block) + _ = ch.receive(rt, consumer) catch |e| { + if (e == error.Closed) { + got_closed.* = true; + return; + } + return e; + }; + @panic("expected error.Closed, but received a value"); }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/sync.zig(9 hunks)
🔇 Additional comments (2)
src/sync.zig (2)
1266-1476: Barrier tests look solid and cover key behaviorsGood coverage: basic sync, leader detection, multi-cycle reuse, single-participant, ordering, and larger N.
1669-1696: BroadcastChannel tests: Barrier-based coordination improves determinismReplacing ad-hoc yields/ResetEvent with Barrier for sender/receiver rendezvous is cleaner and removes timing flakiness. Counts are correct for each test.
Also applies to: 1714-1748, 1946-1977
Split the large src/sync.zig file into a modular structure with individual files for each synchronization primitive. This improves code organization and maintainability. Structure: - Non-generic types use PascalCase filenames (Mutex.zig, Condition.zig, etc.) - Generic types use snake_case filenames (queue.zig, broadcast_channel.zig) - Main sync.zig now re-exports all types from individual modules Files created: - src/sync/Mutex.zig - src/sync/Condition.zig - src/sync/ResetEvent.zig - src/sync/Semaphore.zig - src/sync/Barrier.zig - src/sync/queue.zig - src/sync/broadcast_channel.zig All 77 tests pass after refactoring.
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (8)
src/sync/Mutex.zig (1)
14-19: Fail fast if called outside a coroutineReturning false hides misuse. Trap instead; this should only be called from a coroutine.
pub fn tryLock(self: *Mutex) bool { - const current = coroutines.getCurrent() orelse return false; + const current = coroutines.getCurrent() orelse unreachable; // Try to atomically set owner from null to current return self.owner.cmpxchgStrong(null, current, .acquire, .monotonic) == null; }src/sync/ResetEvent.zig (2)
52-57: Catch misuse: reset while waiters are blocked is UB (add debug guard)Contract says reset during wait is undefined; add a debug assert to surface this early in tests.
pub fn reset(self: *ResetEvent) void { - self.state.store(.unset, .monotonic); + // Undefined to reset while waiters are blocked; catch in debug. + std.debug.assert(self.state.load(.acquire) != .waiting); + self.state.store(.unset, .monotonic); }
62-81: Clarify wake assumption or re-check after yieldwait() assumes wakeups only occur from set(). If spurious wakes are possible in the runtime, re-load state after yield and loop. Otherwise, add a brief comment stating spurious wakes cannot occur.
src/sync/Condition.zig (2)
1-8: Document single‑runtime scope and signaling disciplineAdd a brief note: coroutine‑only (not cross‑thread) and callers should hold the associated mutex when signaling/broadcasting to establish happens‑before on the predicate and avoid missed wakeups.
const AnyTask = @import("../runtime.zig").AnyTask; const Mutex = @import("Mutex.zig"); +/// Condition is a coroutine-only condition variable for a single Runtime (not OS-thread safe). +/// Callers should hold `mutex` when signaling/broadcasting to pair with waiters' release and +/// establish happens-before on the predicate to avoid missed wakeups.
64-76: Signal/broadcast typically under the same mutexTo mirror conventional condvar semantics and reduce races, prefer calling
signal()/broadcast()while holding the associated mutex protecting the predicate (release it afterwards). Tests currently signal without the mutex; consider aligning usage or documenting the deviation.src/sync/Barrier.zig (1)
39-51: Use equality check and assert bounds for robustness
currentcannot exceedcountunder correct usage. Tighten the condition and assert to catch logic bugs earlier.- if (self.current >= self.count) { + std.debug.assert(self.current <= self.count); + if (self.current == self.count) { // Last one to arrive - release everyone self.current = 0; self.generation += 1; self.cond.broadcast(runtime); return true;src/sync/Semaphore.zig (1)
31-53: Optional: rely solely on cond.timedWait for timeout accountingUsing both a Timer and
cond.timedWaitis correct but duplicative. You can simplify by looping only oncond.timedWaitwith the remaining budget, omitting the outer Timer. Behavior stays the same; code gets shorter.src/sync/queue.zig (1)
94-120: Consider consistent closed-checking style.The
putfunction checks for closure inside the wait loop (Line 108), while thegetfunction includes!self.closedin the while condition (Line 52 inget). Both approaches are correct, but using the same pattern in both functions improves consistency and readability.Apply this diff to align
putwithget's style:// Wait while full - while (self.count == self.buffer.len) { + while (self.count == self.buffer.len and !self.closed) { self.not_full.wait(rt, &self.mutex); - // Check if closed while waiting - if (self.closed) { - return error.QueueClosed; - } } + + // Check if closed (same pattern as get()) + if (self.closed) { + return error.QueueClosed; + }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (8)
src/sync.zig(1 hunks)src/sync/Barrier.zig(1 hunks)src/sync/Condition.zig(1 hunks)src/sync/Mutex.zig(1 hunks)src/sync/ResetEvent.zig(1 hunks)src/sync/Semaphore.zig(1 hunks)src/sync/broadcast_channel.zig(1 hunks)src/sync/queue.zig(1 hunks)
🔇 Additional comments (16)
src/sync/Semaphore.zig (1)
16-29: Wake chaining is fine; consider removing the extra signalThe
wait()path signals whenpermits > 0to cascade wakeups. This is correct; alternatively, you can signal only inpost()and let each woken waiter decrement without re-signaling. Current approach is acceptable; no change required.src/sync/Mutex.zig (1)
39-54: Owner pointer correctly references the coroutine field
corois a by-value field inAnyTaskandfromAwaitable/fromCoroutineuse@fieldParentPtrto return the enclosingAnyTask, so&task.corois a*Coroutineas expected.src/sync.zig (2)
12-21: Test re-exports look good.The test block properly references all exported synchronization primitives to ensure they compile. The pattern is consistent and appropriate for Zig's test discovery mechanism.
2-6: Re-exports are correct
Primitive modules (Mutex, Condition, Barrier, etc.) expose multiple symbols and are aliased as namespaces; generic modules (Queue, BroadcastChannel) export only a builder fn and are aliased directly. The AI summary’s.Mutexnotation is incorrect.src/sync/broadcast_channel.zig (7)
7-34: Well-designed broadcast channel with clear documentation.The per-consumer read position tracking via an intrusive linked list is an efficient design that avoids allocations during subscribe/unsubscribe operations. The documentation clearly specifies the single-Runtime constraint.
96-127: Correct lag detection and handling.The
receivefunction properly handles the lag scenario by:
- Checking lag before waiting (Line 101)
- Rechecking lag after waking from wait (Line 112)—this is essential to handle messages written while blocked
- Advancing the consumer to the oldest available message on lag
The closed-channel semantics are also correct: consumers can drain buffered messages before receiving
error.Closed.
157-173: LGTM!The non-blocking send correctly writes to the ring buffer and broadcasts to all waiting consumers. The immediate closed-check prevents writes after closure.
190-232: Excellent use of Barrier for test coordination.The test properly uses
Barrierto ensure the receiver subscribes before the sender begins. This eliminates potential race conditions and demonstrates idiomatic synchronization, which aligns with the PR objectives of refactoring tests to useBarrier.
234-285: LGTM!The test correctly verifies broadcast semantics with multiple consumers using
Barrierto coordinate subscription before sending. All consumers correctly receive all messages.
467-514: LGTM!The test correctly verifies graceful close semantics: buffered messages can be drained before
error.Closedis returned. The use ofBarrierensures proper coordination between sender and receiver.
516-560: LGTM!The test verifies that
close()wakes waiting consumers by broadcasting on the condition variable. TheBarrierensures the consumer is blocked onreceivebeforecloseis called. The logic correctly handles theerror.Closedcase.src/sync/queue.zig (5)
6-29: LGTM!The generic
Queuetype constructor andinitfunction follow standard patterns. The assertion prevents zero-capacity queues, which would cause undefined behavior with modulo operations.
45-70: LGTM!The
getfunction correctly blocks while empty and not closed, then handles the closed-and-empty case after the loop. The ring buffer logic and condition signaling are sound.
143-163: LGTM!The
closefunction correctly broadcasts to bothnot_emptyandnot_fullconditions to wake all waiters. Theimmediateflag provides both graceful and abrupt close semantics.
167-201: LGTM!The test correctly verifies basic FIFO behavior with blocking put/get operations. The queue's internal synchronization ensures correct ordering.
348-383: LGTM!The test correctly verifies graceful close semantics: buffered items can be drained before
error.QueueClosedis returned. This mirrors the BroadcastChannel's close behavior.
The Work callback function signature has been simplified from fn(loop: *Loop, work: *Work) void to fn(work: *Work) void. The Loop parameter was unnecessary since work functions that need access to the Loop can retrieve it from work.loop. This simplifies the API and makes it more consistent with other callback patterns.
Summary
This PR introduces a new
Barriersynchronization primitive for coordinating multiple coroutines at a synchronization point, and refactors theBroadcastChanneltests to use it instead ofResetEventand atomic counters.Changes
New Barrier primitive:
truefor the last coroutine to arrive (the "leader")BroadcastChannel test refactoring:
ResetEvent+ atomic counters withBarrierfor cleaner coordinationBenefits
Summary by CodeRabbit