Skip to content

Add async-aware Mutex and Condition synchronization primitives - #4

Merged
lalinsky merged 6 commits into
mainfrom
async-sync-primitives
Sep 27, 2025
Merged

lalinsky merged 6 commits into
mainfrom
async-sync-primitives

Conversation

@lalinsky

@lalinsky lalinsky commented Sep 26, 2025 •

Copy link
Copy Markdown
Owner

Summary

This PR implements coroutine-aware synchronization primitives for the ZIO async runtime, providing Mutex and Condition that work seamlessly with the existing coroutine scheduler.

Features Added

  • ✅ Async Mutex - Non-blocking mutex with coroutine suspension
  • ✅ Async Condition - Condition variables with wait/signal/broadcast semantics
  • ✅ API Compatibility - Matches std.Thread.Mutex/std.Thread.Condition interfaces
  • ✅ Timer Support - timedWait() with libxev integration
  • ✅ Example Programs - Mutex demo and producer-consumer patterns

Implementation Highlights

  • Race-condition free: Single atomic owner field eliminates dual-state races
  • Efficient ownership transfer: Direct handoff from unlock() to next waiter
  • Proper memory ordering: Uses acquire/release semantics throughout
  • Runtime integration: Leverages existing AnyTaskList and scheduling infrastructure

API Overview

// Mutex - same API as std.Thread.Mutex
var mutex = zio.Mutex.init(&runtime);
mutex.lock();
defer mutex.unlock();
if (mutex.tryLock()) { /* got lock */ }

// Condition - same API as std.Thread.Condition  
var cond = zio.Condition.init(&runtime);
cond.wait(&mutex);                          // Wait for signal
cond.timedWait(&mutex, timeout_ns) catch {}; // Wait with timeout
cond.signal();                               // Wake one waiter
cond.broadcast();                            // Wake all waiters

Testing

  • mutex_demo.zig: 4 coroutines incrementing shared counter (4000 operations)
  • producer_consumer.zig: 2 producers + 2 consumers with bounded buffer
  • Both examples demonstrate correct synchronization without race conditions

Test plan

  • Build succeeds with zig build
  • Mutex demo produces correct result (counter = 4000)
  • Producer-consumer demo shows proper coordination
  • No race conditions observed in concurrent access patterns
  • timedWait timeout functionality works correctly

Summary by CodeRabbit

  • New Features

    • Added synchronization primitives: Mutex and Condition with locking, timed waits, signal, and broadcast for coordinated tasks.
    • Primitives exposed in the public API.
  • Documentation

    • Added runnable examples:
      • Mutex-protected counter demonstrating concurrent increments and final-count logging.
      • Producer–consumer bounded-buffer showing backpressure, signaling, and progress/final-state logs.

This commit implements coroutine-aware synchronization primitives that integrate
with the ZIO async runtime:

## Features
- **Async Mutex**: Provides lock(), unlock(), tryLock() with coroutine suspension
- **Async Condition**: Provides wait(), timedWait(), signal(), broadcast() semantics
- **API Compatibility**: Matches std.Thread.Mutex/Condition interfaces exactly
- **Runtime Integration**: Uses existing AnyTaskList and markReady/waitForReady infrastructure

## Implementation Details
- Single atomic owner field eliminates race conditions between lock state and ownership
- Direct ownership transfer from unlock() to next waiter for efficiency
- libxev timer integration for timedWait() timeout support
- Proper memory ordering with acquire/release semantics

## Examples
- mutex_demo.zig: Multi-coroutine counter with mutex protection
- producer_consumer.zig: Bounded buffer using Mutex + Condition variables

## Changes
- src/sync.zig: New synchronization primitives implementation
- src/zio.zig: Export Mutex and Condition
- src/runtime.zig: Make markReady and taskPtrFromCoroPtr public
- build.zig: Add new example executables
- examples/: Demonstration programs

Tested with both examples showing correct mutual exclusion and coordination.
@coderabbitai

coderabbitai Bot commented Sep 26, 2025 •

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

@lalinsky has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 1 minutes and 8 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between b1325ff and 29dcd73.

📒 Files selected for processing (3)
  • src/runtime.zig (2 hunks)
  • src/sync.zig (1 hunks)
  • src/zio.zig (2 hunks)

Walkthrough

Adds Mutex and Condition synchronization primitives with wait queues and timed waits, re-exports them via src/zio.zig, adds two new examples (mutex-demo, producer-consumer), and registers those examples in build.zig.

Changes

Cohort / File(s) Summary
Build — example entries
build.zig
Adds two example executables to the examples loop: mutex-demo and producer-consumer.
Sync primitives
src/sync.zig
Adds public Mutex (owner CAS, wait queue, init/tryLock/lock/unlock) and public Condition (wait/timedWait/signal/broadcast) integrated with the runtime and coroutine scheduling.
Public API re-exports
src/zio.zig
Re-exports Mutex and Condition from sync.zig as public constants.
Examples — new demos
examples/mutex_demo.zig, examples/producer_consumer.zig
Adds a mutex-protected counter demo and a bounded-buffer producer–consumer demo using zio.Runtime, Mutex, and Condition.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Task
  participant Mutex
  participant Runtime
  participant WaitQueue as Mutex.wait_queue

  Note over Task,Mutex: Mutex.lock fast/slow path
  Task->>Mutex: tryLock()
  alt CAS succeeds
    Mutex-->>Task: acquired
  else CAS fails
    Task->>WaitQueue: enqueue(Task)
    Task->>Runtime: suspend()
    Runtime-->>Task: wake on ownership transfer
    Mutex-->>Task: assert owner == Task
  end
  Note over Task,Mutex: unlock
  Task->>Mutex: unlock()
  alt waiters exist
    Mutex->>WaitQueue: pop next
    Mutex->>Runtime: transfer owner + wake(next)
  else
    Mutex-->>Task: owner = null
  end
Loading
sequenceDiagram
  autonumber
  actor Task as Waiting Task
  participant Cond as Condition
  participant M as Mutex
  participant Runtime
  participant Q as Condition.wait_queue

  Note over Task,Cond: Condition.wait
  Task->>Q: enqueue(Task)
  Task->>M: unlock()
  Task->>Runtime: suspend()
  Runtime-->>Task: wake (signal/broadcast/timeout)
  Task->>M: lock()
  Cond-->>Task: resume with lock held

  Note over Cond,Runtime: signal/broadcast
  participant Signaller
  Signaller->>Cond: signal()/broadcast()
  alt signal
    Cond->>Q: pop one
    Cond->>Runtime: wake(one)
  else broadcast
    Cond->>Q: drain all
    Cond->>Runtime: wake(all)
  end
Loading
sequenceDiagram
  autonumber
  actor P1 as Producer 1
  actor P2 as Producer 2
  actor C1 as Consumer 1
  actor C2 as Consumer 2
  participant Buf as BoundedBuffer
  participant M as Mutex
  participant NE as not_empty
  participant NF as not_full

  rect rgba(230,245,255,0.4)
  Note right of P1: put(item)
  P1->>M: lock()
  alt buffer full
    P1->>NF: wait(M)
  end
  P1->>Buf: enqueue
  P1->>NE: signal()
  P1->>M: unlock()
  end

  rect rgba(240,230,255,0.4)
  Note right of C1: get()
  C1->>M: lock()
  alt buffer empty
    C1->>NE: wait(M)
  end
  C1->>Buf: dequeue
  C1->>NF: signal()
  C1->>M: unlock()
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

I tap my paw—a lock, a key,
Queues of dreams in coroutines free.
A nibble produced, a nibble consumed,
Signals bloom where waits once loomed.
With Mutex snug and Conditions bright,
I hop through race-free moonlit night. 🐇🔒✨

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 pull request title clearly and concisely describes the primary change: adding async-aware Mutex and Condition synchronization primitives to the runtime. It uses precise terminology that aligns with the implemented APIs and avoids extraneous details.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.

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.

- Keep new build.zig structure without step/desc fields
- Add mutex-demo and producer-consumer examples
- Include new tls-demo example from main branch

@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: 3

🧹 Nitpick comments (3)
src/runtime.zig (1)

292-296: Consider documenting thread-safety guarantees for taskPtrFromCoroPtr.

This function performs unsafe pointer arithmetic to convert between coroutine and task pointers. While the implementation is correct, the public API would benefit from documentation about its thread-safety guarantees and valid usage contexts (e.g., should only be called with coroutines owned by this runtime).

Consider adding a doc comment:

+    /// Converts a Coroutine pointer to its containing Task node pointer.
+    /// Safety: The coroutine must be owned by this runtime and the pointer must remain valid.
+    /// Thread-safety: This function itself is thread-safe but the returned pointer
+    /// must be used according to the synchronization rules of the containing data structures.
     pub inline fn taskPtrFromCoroPtr(coro: *Coroutine) *AnyTaskList.Node {
examples/producer_consumer.zig (2)

76-77: Consider validating consumed items.

The consumer function retrieves items but doesn't use them (_ = item). For a more robust demo, consider validating or processing the consumed items to demonstrate data integrity under concurrent access.

     for (0..5) |_| {
         const item = buffer.get();
-        _ = item;
+        // Could validate item format or accumulate for verification
+        std.debug.assert(item >= 0 and item < 1000); // Basic sanity check
         rt.sleep(150); // Small delay between consumptions
     }

65-81: Consider making iteration counts configurable.

Both producer and consumer functions hard-code 5 iterations. For better demo flexibility and testing different scenarios, consider making this configurable.

-fn producer(rt: *zio.Runtime, buffer: *BoundedBuffer, id: u32) void {
-    for (0..5) |i| {
+fn producer(rt: *zio.Runtime, buffer: *BoundedBuffer, id: u32, count: u32) void {
+    for (0..count) |i| {
         const item = @as(i32, @intCast(id * 100 + i));
         buffer.put(item);
         rt.sleep(100); // Small delay between productions
     }
     std.log.info("Producer {} finished", .{id});
 }

-fn consumer(rt: *zio.Runtime, buffer: *BoundedBuffer, id: u32) void {
-    for (0..5) |_| {
+fn consumer(rt: *zio.Runtime, buffer: *BoundedBuffer, id: u32, count: u32) void {
+    for (0..count) |_| {
         const item = buffer.get();
         _ = item;
         rt.sleep(150); // Small delay between consumptions
     }
     std.log.info("Consumer {} finished", .{id});
 }

Then update the spawn calls:

+    const items_per_task = 5;
     for (0..2) |i| {
-        producers[i] = try runtime.spawn(producer, .{ &runtime, &buffer, @as(u32, @intCast(i)) }, .{});
-        consumers[i] = try runtime.spawn(consumer, .{ &runtime, &buffer, @as(u32, @intCast(i)) }, .{});
+        producers[i] = try runtime.spawn(producer, .{ &runtime, &buffer, @as(u32, @intCast(i)), items_per_task }, .{});
+        consumers[i] = try runtime.spawn(consumer, .{ &runtime, &buffer, @as(u32, @intCast(i)), items_per_task }, .{});
     }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 65f8ad2 and 006d562.

📒 Files selected for processing (6)
  • build.zig (1 hunks)
  • examples/mutex_demo.zig (1 hunks)
  • examples/producer_consumer.zig (1 hunks)
  • src/runtime.zig (1 hunks)
  • src/sync.zig (1 hunks)
  • src/zio.zig (1 hunks)
🔇 Additional comments (6)
build.zig (1)

33-34: LGTM! New examples properly integrated.

The new mutex and producer-consumer demos are correctly added to the examples configuration and will be built automatically with the existing build loop.

src/zio.zig (1)

24-26: LGTM! Clean public API exports.

The synchronization primitives are properly exposed through the public zio module interface, maintaining consistency with the existing export pattern.

src/runtime.zig (1)

298-303: LGTM! Proper state validation and scheduling.

The markReady function correctly validates coroutine state before transitioning and properly enqueues the task for scheduling.

examples/mutex_demo.zig (1)

36-40: LGTM! Proper resource management with defer.

The task array initialization and cleanup with defer ensures all tasks are properly cleaned up even if runtime.run() fails.

examples/producer_consumer.zig (2)

4-20: Well-structured bounded buffer implementation.

The BoundedBuffer correctly implements the classic producer-consumer pattern with proper synchronization using mutex and condition variables. The ring buffer implementation with head/tail pointers is efficient.


101-104: LGTM! Proper cleanup ordering.

The defer block ensures both producer and consumer tasks are properly cleaned up, maintaining correct resource management even if runtime.run() fails.

Comment thread examples/mutex_demo.zig Resolved
Comment thread src/sync.zig Resolved
Comment thread src/sync.zig Resolved
The timer callback now atomically removes the task from the wait queue
before setting the timeout flag, preventing race conditions where a
signal could arrive after timeout but before the manual cleanup,
leading to false timeout errors and potential double-removal issues.
Upgrade the ownership check from monotonic to acquire ordering to
complete the release/acquire handshake with unlock(), ensuring
memory writes protected by the mutex are visible to the new owner.

@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: 2

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 099667c and b1325ff.

📒 Files selected for processing (1)
  • src/sync.zig (1 hunks)
🔇 Additional comments (1)
src/sync.zig (1)

37-38: Restore acquire semantics on slow-path owner check.
The resumed waiter still issues a .monotonic load on self.owner, so it never pairs with the .release store in unlock. Without the acquire fence, writes protected by the mutex can remain invisible to the new owner. Switch this load to .acquire (while keeping the assert) to close the release/acquire handshake.

Apply this diff:

-        std.debug.assert(self.owner.load(.monotonic) == current);
+        const owner = self.owner.load(.acquire);
+        std.debug.assert(owner == current);

Comment thread src/sync.zig Resolved
Comment thread src/sync.zig Resolved
@lalinsky
lalinsky merged commit dc2d52e into main Sep 27, 2025
@lalinsky
lalinsky deleted the async-sync-primitives branch September 27, 2025 05:27
lalinsky added a commit that referenced this pull request Jan 6, 2026
lalinsky added a commit that referenced this pull request Jan 6, 2026
@coderabbitai coderabbitai Bot mentioned this pull request Feb 24, 2026
5 tasks done
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