Repository navigation
Add Semaphore synchronization primitive - #22
Conversation
Implements a coroutine-safe counting semaphore matching the std.Thread.Semaphore API. Supports wait(), timedWait(), and post() operations for coordinating access to limited resources across coroutines.
WalkthroughAdds a coroutine-safe counting Semaphore (wait, timedWait, post) in Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant C as Coroutine
participant S as Semaphore
participant M as Mutex
participant V as Condition
participant R as Runtime/Timer
rect rgb(250,250,255)
Note over C,S: wait(rt)
C->>S: wait(rt)
S->>M: lock()
alt permits == 0
S->>V: wait(rt) (block)
V-->>S: awakened (post)
end
S->>S: decrement permits
S->>M: unlock()
C-->>C: resume
end
rect rgb(245,255,245)
Note over C,S: timedWait(rt, timeout_ns)
C->>S: timedWait(rt, ns)
S->>M: lock()
alt permits == 0
S->>R: start timer -> on timeout: markReady(current)
S->>V: timed wait(rt, ns)
alt timeout
V-->>R: timeout fires -> coroutine resumed with error.Timeout
S->>M: unlock()
else awakened
V->>R: cancel timer, wait-for-cancel
S->>S: decrement permits
S->>M: unlock()
end
else permits > 0
S->>S: decrement permits
S->>M: unlock()
end
end
rect rgb(255,245,245)
Note over C,S: post(rt)
C->>S: post(rt)
S->>M: lock()
S->>S: increment permits
S->>V: signal one waiter
S->>M: unlock()
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 |
|
@claude for some reason, the code is crashing on macos, see if you can find a possible reason |
|
Claude finished @lalinsky's task —— View job macOS Crash Analysis - Found the Issue! ✓I've identified the root cause of the macOS crash in the Semaphore implementation. Issue DetailsCrash Location: Stack Trace: The crash occurs in libxev's heap implementation when managing timers: Root CauseThe problem is in pub fn timedWait(self: *Semaphore, rt: *Runtime, timeout_ns: u64) error{Timeout}!void {
var timeout_timer = std.time.Timer.start() catch unreachable; // Line 1144
self.mutex.lock(rt);
defer self.mutex.unlock(rt);
while (self.permits == 0) {
const elapsed = timeout_timer.read();
if (elapsed > timeout_ns) {
return error.Timeout;
}
const local_timeout_ns = timeout_ns - elapsed;
try self.cond.timedWait(rt, &self.mutex, local_timeout_ns); // Line 1156
}
// ... rest of code
}When
This is a use-after-free bug. The same issue exists in Why It's macOS-SpecificThe crash is macOS-specific due to:
SolutionThe timer and completion structs must outlive the coroutine suspension. Options:
The same fix needs to be applied to:
RecommendationI recommend looking at how other sync primitives handle this, or checking if libxev provides a pattern for this. The timer and completion need to be allocated in a way that survives coroutine suspension. Would you like me to implement a fix for this issue? Job run • Branch: |
|
@claude the watcher/completion should survive suspend just fine, the coroutine stack exists for as long as the coroutine is alive. Maybe the problem is that we are not cancelling the timer? |
|
Claude finished @lalinsky's task —— View job Analysis Complete - Found the Root Cause ✓You're absolutely right that coroutine stacks survive suspension. After thorough analysis, here's what's actually happening: The Root CauseThe bug is in The Problem:
Key InsightWhile the coroutine stack survives suspension, the function's local variables ( From pub fn deinit(self: *const Self) void {
// Nothing for now.
_ = self;
}The Fix NeededThe timer must be explicitly cancelled when waking via signal (non-timeout path). This requires using
This would add complexity. Do you have a preferred approach for handling this, or should I look for similar patterns elsewhere in the codebase? Job run • Branch: |
|
@claude implement it by cancelling the timer and waiting for the cancellation to complete |
|
Claude finished @lalinsky's task —— View job Timer Cancellation Fix Complete ✓Successfully implemented timer cancellation to fix the macOS crash when timedWait succeeds early via signal. What Was FixedThe bug occurred when Changes MadeCondition.timedWait() (src/sync.zig:146-178)
ResetEvent.timedWait() (src/sync.zig:350-380)
Semaphore.timedWait()
Test Results✅ All Semaphore tests pass (4/4) Tasks Completed
Job run • Branch: |
When timedWait succeeds early (via signal/set), the timer must be explicitly cancelled to prevent the event loop from accessing freed stack memory when the timer fires later. Added timer.cancel() calls with proper cancellation completion handling in both Condition.timedWait() and ResetEvent.timedWait(). Semaphore.timedWait() is automatically fixed as it delegates to Condition.timedWait(). 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Lukáš Lalinský <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
src/sync.zig (1)
145-179: Consider extracting timer cancellation logic to reduce duplication.The timer cancellation pattern (lines 146-171) is duplicated in
ResetEvent.timedWait(lines 349-375). Consider extracting this into a helper function to improve maintainability.Additionally, the busy-wait pattern (lines 175-177) using
runtime.loop.run(.no_wait)in a tight loop could consume unnecessary CPU cycles. While the wait is expected to be brief, a small sleep or a more event-driven approach might be more efficient.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/sync.zig(3 hunks)
🔇 Additional comments (3)
src/sync.zig (3)
1193-1205: LGTM: Well-designed wait implementation.The signal optimization (lines 1202-1204) that wakes the next waiter when
permits > 0after decrement is essential for correctness. Without it, multiple waiters could remain blocked even when permits are available. This matches the behavior ofstd.Thread.Semaphoreand ensures fair resource distribution.
1209-1229: LGTM: Correct timedWait implementation.The approach of using
std.time.Timerto track elapsed time and adjusting the timeout for eachcond.timedWaitcall is sound. While minor timing inaccuracies could theoretically accumulate across multiple wait/wakeup cycles, this is acceptable for typical semaphore use cases and matches the expected behavior.The immediate error propagation on line 1222 is correct because the condition variable's
wait_queue.remove()operation serves as a race resolver betweensignal()and the timeout callback.
1241-1352: LGTM: Good test coverage for Semaphore.The four tests effectively cover the key scenarios:
- Basic mutual exclusion with multiple waiters (lines 1241-1268)
- Timeout behavior when no permits available (lines 1270-1293)
- Successful acquisition within timeout window (lines 1295-1325)
- Multiple-permit behavior (lines 1327-1352)
This provides solid confidence in the core functionality of the Semaphore implementation.
|
@claude you should not call loop, but rather waitForReady |
|
Claude finished @lalinsky's task —— View job Timer Cancellation Fix Complete ✓Successfully replaced the busy-wait loop with proper coroutine suspension using Changes MadeCondition.timedWait() (src/sync.zig:146-185)
ResetEvent.timedWait() (src/sync.zig:357-394)
Test Results✅ All Semaphore tests pass (5/5 tests)
Tasks Completed
Job run • Branch: |
Replace runtime.loop.run(.no_wait) busy-wait with proper coroutine suspension using waitForReady() in Condition.timedWait() and ResetEvent.timedWait(). Co-authored-by: Lukáš Lalinský <[email protected]>
|
@claude consider if it would make sense to add rt.timedWaitForReady(timeout_ns) and if so, what would it look like. Don't change code yet, just analyze and design. |
|
Claude finished @lalinsky's task —— View job Analyzing
|
|
@claude implement it |
|
Claude finished @lalinsky's task —— View job Implementation Complete ✓Successfully implemented What Was ImplementedNew Runtime Method (src/runtime.zig:704-783)
Implementation DetailsThe method follows the two-wait pattern:
This prevents the macOS crash bug where timers would fire after stack frames were unwound. Design ConsiderationsWhy existing Both methods require custom timeout callbacks that remove waiters from their wait queues (lines 124, 339 in sync.zig). The timeout callback acts as a race resolver between timeout and signal/set. Simply using Value of the new API:
Test Results✅ All Semaphore tests pass (5/5) Changes Committed
Job run • Branch: |
Implements a new runtime primitive that suspends the current coroutine for up to timeout_ns nanoseconds, with proper timer cancellation to prevent use-after-scope bugs. This provides a building block for future sync primitives that need simple timeout behavior without custom wait queue management. Co-authored-by: Lukáš Lalinský <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
src/runtime.zig (1)
704-783: Implementation correctly addresses the macOS crash by canceling the timer.The timer cancellation logic (lines 757-782) prevents the timer callback from accessing the stack-allocated
ctxafter the function returns, which was causing the reported crash. The dual-path approach (timeout vs. external wake) is sound.However, consider these improvements:
Timeout precision loss: Line 727 converts nanoseconds to milliseconds with integer division (
timeout_ns / 1_000_000). Timeouts less than 1ms will round down to 0. If sub-millisecond precision is needed, this could be problematic.Missing documentation: Add doc comments explaining the method's purpose, parameters, error conditions, and the guarantee that the timer will be properly canceled regardless of which event fires first.
Example documentation:
/// Waits for the current coroutine to be marked ready by an external event, /// with a timeout. If the timeout expires before an external markReady call, /// returns error.Timeout. If awakened by external markReady, cancels the /// timer and waits for cancellation to complete before returning. /// /// Must be called from within a coroutine context. /// /// @param timeout_ns Timeout in nanoseconds (converted to milliseconds, rounded down) /// @return error.Timeout if the timeout expires, otherwise void on success pub fn timedWaitForReady(self: *Runtime, timeout_ns: u64) error{Timeout}!void {
* Refactor completion error handling to separate errors from payloads This commit refactors the completion system to store errors separately from result payloads, improving clarity and type safety. Key changes: - Added err and has_result fields to base Completion struct - Changed operation result fields from Error!Payload to Payload - Renamed result fields to result_private_do_not_touch to prevent direct access - Updated setResult/setError to handle cancelation race conditions - Changed getResult API to take comptime operation type parameter - Updated all backends (io_uring, epoll, kqueue, poll) to use new pattern - Updated all tests to use getResult() methods The new pattern requires calling setResult(.operation_type, value) and getResult(.operation_type) instead of directly accessing result fields. * Server test * Refactor EchoServer and EchoClient to use comptime sockaddr types Instead of using unions to store different sockaddr types, both EchoServer and EchoClient now accept the sockaddr type as a comptime parameter. This eliminates the need for runtime unions and separate length fields, making the code more type-safe and efficient. Changes: - Add sockaddr as comptime type parameter to both functions - Remove union-based server_addr and connect_addr fields - Remove server_addr_len and connect_addr_len fields - Use @sizeof(sockaddr) for address length - Use std.mem.sliceTo() for null-terminated path slices - Simplify address initialization with direct field assignment * Simplify server test by removing redundant state tracking Remove the tagged union enum in favor of plain unions, since the State enum already tracks the current state. This eliminates redundancy. Also simplify bindCallback to update server_addr in place with getsockname, removing the need for a separate bound_port field and domain-specific switch logic. Simplify EchoClient by accepting the full server_addr instead of conditional port/path parameters, removing all address construction logic from openCallback. Changes: - Remove union(enum) tags, use plain unions - Remove bound_port field from EchoServer - Simplify bindCallback to call getsockname once for all socket types - Change EchoClient.init() to accept full sockaddr - Remove address construction code from EchoClient.openCallback - Simplify test to pass server.server_addr directly to client * Skip Unix socket test on Windows * Move builtin import to top of file * Fix macOS compatibility by using time.now() instead of std.os.linux.getpid() * Handle partial writes in echo server * Rename server.zig to stream_server.zig and add dgram_server.zig * Add shutdown after send in stream client * Refactor net_bind to update address * Fix common.zig socket API calls for cross-platform compatibility - Change socket.open() to socket.socket() with correct parameters - Fix socket.close() which returns void, not error union - Ensures builds work on FreeBSD, NetBSD, and macOS * Oops * Fix echo server to read after send and detect EOF After echoing data back to the client, the server now returns to the receiving state instead of immediately closing. This allows it to properly detect when the client shuts down (EOF), at which point it closes the connection gracefully. * Handle partial writes in echo client Track bytes_sent and re-issue NetSend with the remaining slice until all data is sent. This prevents calling shutdown(.send) early when a short write occurs, which would cause the server to only read and echo back a prefix of the message. * Let client drain the full echo response Continue reading and accumulating bytes_received until EOF (0 bytes) instead of closing after the first NetRecv. This handles cases where the server's echo response is delivered across multiple completions, preventing data loss and assertion failures.

Summary
Semaphoreinsrc/sync.zigmatching thestd.Thread.SemaphoreAPIwait(),timedWait(), andpost()methods for coroutine-safe resource countingziomoduleImplementation
MutexandConditionprimitivesTest plan
./check.sh --test-filter "Semaphore"passesSummary by CodeRabbit