Repository navigation
Add async-aware Mutex and Condition synchronization primitives - #4
Conversation
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.
|
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 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. 📒 Files selected for processing (3)
WalkthroughAdds Mutex and Condition synchronization primitives with wait queues and timed waits, re-exports them via Changes
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
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
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
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 |
- Keep new build.zig structure without step/desc fields - Add mutex-demo and producer-consumer examples - Include new tls-demo example from main branch
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (3)
src/runtime.zig (1)
292-296: Consider documenting thread-safety guarantees fortaskPtrFromCoroPtr.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
📒 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
markReadyfunction 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.
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.
There was a problem hiding this comment.
Actionable comments posted: 2
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 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.monotonicload onself.owner, so it never pairs with the.releasestore inunlock. 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);
…139309 Add Claude Code GitHub Workflow
Summary
This PR implements coroutine-aware synchronization primitives for the ZIO async runtime, providing
MutexandConditionthat work seamlessly with the existing coroutine scheduler.Features Added
std.Thread.Mutex/std.Thread.ConditioninterfacestimedWait()with libxev integrationImplementation Highlights
ownerfield eliminates dual-state racesAnyTaskListand scheduling infrastructureAPI Overview
Testing
Test plan
zig buildSummary by CodeRabbit
New Features
Documentation