Skip to content

Add Barrier synchronization primitive and refactor BroadcastChannel tests - #40

Merged
lalinsky merged 2 commits into
mainfrom
refactor-broadcast-channel-tests-barrier
Oct 9, 2025
Merged

lalinsky merged 2 commits into
mainfrom
refactor-broadcast-channel-tests-barrier

Conversation

@lalinsky

@lalinsky lalinsky commented Oct 9, 2025 •

Copy link
Copy Markdown
Owner

Summary

This PR introduces a new Barrier synchronization primitive for coordinating multiple coroutines at a synchronization point, and refactors the BroadcastChannel tests to use it instead of ResetEvent and atomic counters.

Changes

New Barrier primitive:

  • Allows a fixed number of coroutines to synchronize at a common point
  • Uses generation-based tracking to support reuse across multiple cycles
  • Returns true for the last coroutine to arrive (the "leader")
  • Includes comprehensive test coverage:
    • Basic synchronization with multiple coroutines
    • Leader detection
    • Multiple reuse cycles
    • Single coroutine edge case
    • Ordering verification
    • Stress test with many coroutines

BroadcastChannel test refactoring:

  • Replaced ResetEvent + atomic counters with Barrier for cleaner coordination
  • Simplified synchronization logic in 4 tests:
    • Basic send and receive
    • Multiple consumers
    • Consumers can drain after close
    • Waiting consumers wake on close

Benefits

  • More idiomatic synchronization pattern for test coordination
  • Cleaner, more readable test code
  • Barrier primitive is now available for use in other tests and potentially production code
  • Eliminates manual atomic counter management in tests

Summary by CodeRabbit

  • New Features
    • Added a collection of synchronization primitives and concurrency utilities: Mutex, Condition, ResetEvent, Semaphore, Barrier, bounded Queue, and BroadcastChannel.
  • Refactor
    • Consolidated synchronization APIs into modular exports for a cleaner public surface.
  • Tests
    • Extensive new tests validating behavior, timeouts, multi-consumer scenarios, and multi-cycle/leader semantics.

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

coderabbitai Bot commented Oct 9, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Replaces in-file synchronization implementations with dedicated modules and public re-exports from src/sync.zig. Adds new module files implementing Mutex, Condition, ResetEvent, Semaphore, Barrier, Queue, and BroadcastChannel, each with unit tests and runtime-integrated coroutine semantics.

Changes

Cohort / File(s) Summary
Public re-exports
src/sync.zig
Removes embedded primitive implementations and re-exports primitives: Mutex, Condition, ResetEvent, Semaphore, Barrier, Queue, and BroadcastChannel from their respective src/sync/* modules.
Mutex implementation
src/sync/Mutex.zig
New Mutex type with atomic owner, init, tryLock, lock, unlock, waiter queue integration with Runtime; includes tests for concurrent locking and tryLock behavior.
Condition variable
src/sync/Condition.zig
New Condition type with wait, timedWait, signal, broadcast; integrates with Runtime awaitables and mutex handoff; includes tests (wait/signal, timed wait, broadcast).
ResetEvent
src/sync/ResetEvent.zig
New ResetEvent with atomic state, isSet, set, reset, wait, timedWait; uses awaitable queue and atomic transitions; comprehensive tests.
Semaphore
src/sync/Semaphore.zig
New counting Semaphore using Mutex and Condition: wait, timedWait, post; tests for wait/post, timeouts, multiple permits.
Barrier
src/sync/Barrier.zig
New reusable Barrier primitive with init(count) and wait(runtime) -> bool leader detection; uses Mutex+Condition and supports multi-cycle reuse; tests for basic, leader, and multi-cycle behavior.
Bounded queue
src/sync/queue.zig
New generic Queue(comptime T) ring-buffer with init, isEmpty, isFull, blocking get/put, non-blocking tryGet/tryPut, close(immediate) and tests covering concurrency and close semantics.
Broadcast channel
src/sync/broadcast_channel.zig
New generic BroadcastChannel(comptime T) with fixed ring buffer, per-consumer positions, subscribe/unsubscribe, blocking receive/non-blocking tryReceive, send, close; handles lagging consumers and draining; includes tests.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

I thump my foot and count the crew,
We wait, we hop, we pass on through.
Leader springs when last one lands,
Coroutines clap with twitching hands.
Reused cycles, neat and clever—hare-approved forever. 🐇✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title accurately captures the two primary changes of the pull request by naming the new Barrier synchronization primitive and the refactoring of BroadcastChannel tests, providing a clear and concise summary of the PR’s intent.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch refactor-broadcast-channel-tests-barrier

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/sync.zig (2)

1218-1264: Barrier: tighten arrival condition and add bounds assert

Use 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 waiter

Use 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

📥 Commits

Reviewing files that changed from the base of the PR and between 277032f and aa1654b.

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

Good coverage: basic sync, leader detection, multi-cycle reuse, single-participant, ordering, and larger N.


1669-1696: BroadcastChannel tests: Barrier-based coordination improves determinism

Replacing 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.
@lalinsky
lalinsky merged commit 4a29087 into main Oct 9, 2025
@lalinsky
lalinsky deleted the refactor-broadcast-channel-tests-barrier branch October 9, 2025 13:33

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (8)
src/sync/Mutex.zig (1)

14-19: Fail fast if called outside a coroutine

Returning 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 yield

wait() 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 discipline

Add 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 mutex

To 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

current cannot exceed count under 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 accounting

Using both a Timer and cond.timedWait is correct but duplicative. You can simplify by looping only on cond.timedWait with 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 put function checks for closure inside the wait loop (Line 108), while the get function includes !self.closed in the while condition (Line 52 in get). Both approaches are correct, but using the same pattern in both functions improves consistency and readability.

Apply this diff to align put with get'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

📥 Commits

Reviewing files that changed from the base of the PR and between aa1654b and ab940bf.

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

The wait() path signals when permits > 0 to cascade wakeups. This is correct; alternatively, you can signal only in post() 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
coro is a by-value field in AnyTask and fromAwaitable/fromCoroutine use @fieldParentPtr to return the enclosing AnyTask, so &task.coro is a *Coroutine as 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 .Mutex notation 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 receive function properly handles the lag scenario by:

  1. Checking lag before waiting (Line 101)
  2. Rechecking lag after waking from wait (Line 112)—this is essential to handle messages written while blocked
  3. 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 Barrier to 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 use Barrier.


234-285: LGTM!

The test correctly verifies broadcast semantics with multiple consumers using Barrier to 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.Closed is returned. The use of Barrier ensures proper coordination between sender and receiver.


516-560: LGTM!

The test verifies that close() wakes waiting consumers by broadcasting on the condition variable. The Barrier ensures the consumer is blocked on receive before close is called. The logic correctly handles the error.Closed case.

src/sync/queue.zig (5)

6-29: LGTM!

The generic Queue type constructor and init function follow standard patterns. The assertion prevents zero-capacity queues, which would cause undefined behavior with modulo operations.


45-70: LGTM!

The get function 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 close function correctly broadcasts to both not_empty and not_full conditions to wake all waiters. The immediate flag 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.QueueClosed is returned. This mirrors the BroadcastChannel's close behavior.

lalinsky added a commit that referenced this pull request Jan 6, 2026
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.
@coderabbitai coderabbitai Bot mentioned this pull request Feb 7, 2026
1 of 2 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant