Skip to content

Refactor sync primitives and add Queue(T) - #21

Merged
lalinsky merged 3 commits into
mainfrom
sync-queue-implementation
Oct 4, 2025
Merged

lalinsky merged 3 commits into
mainfrom
sync-queue-implementation

Conversation

@lalinsky

@lalinsky lalinsky commented Oct 4, 2025 •

Copy link
Copy Markdown
Owner

Summary

  • Refactored Mutex, Condition, and ResetEvent to remove stored Runtime reference
  • Implemented Queue(T) - a coroutine-safe bounded FIFO queue with ring buffer

Changes to existing sync primitives

  • Changed init(runtime: *Runtime) to constant init: Type = .{}
  • All methods now take rt: *Runtime as parameter
  • Updated all call sites in src/net.zig and src/tcp.zig

Queue(T) implementation

  • Coroutine-safe for multiple producers/consumers within a single Runtime
  • Blocking operations: get() and put()
  • Non-blocking operations: tryGet() and tryPut()
  • Graceful and immediate close modes via close(rt, immediate: bool)
  • Helper methods: isEmpty() and isFull()
  • Implemented as ring buffer for efficient memory usage

Test plan

  • All existing tests pass (50/50)
  • Added 9 comprehensive tests for Queue:
    • Basic put/get operations
    • Blocking and non-blocking behavior
    • Multiple producers/consumers
    • Close behavior (graceful/immediate)
    • Ring buffer wrapping
    • Error handling (QueueClosed, QueueEmpty, QueueFull)

Summary by CodeRabbit

  • New Features
    • Added a generic bounded FIFO Queue for coroutine producer-consumer patterns, with blocking/try operations and close semantics.
  • Refactor
    • Synchronization primitives updated to be runtime-aware with simplified initialization; locking/waiting/signaling now require an explicit runtime (breaking API change).
  • Tests / Examples
    • Tests and examples updated to match the new synchronization and Queue APIs.
  • Documentation
    • Features list updated to include Queue.

- Refactored Mutex, Condition, and ResetEvent to not store Runtime
  - Changed init() from function to constant init: Type = .{}
  - All methods now take rt: *Runtime as parameter
  - Updated all call sites in src/net.zig and src/tcp.zig

- Implemented Queue(T) bounded FIFO queue with ring buffer
  - Coroutine-safe for multiple producers/consumers within single Runtime
  - Blocking operations: get() and put()
  - Non-blocking operations: tryGet() and tryPut()
  - Graceful and immediate close modes
  - Helper methods: isEmpty() and isFull()

- Added comprehensive tests for Queue functionality
  - Basic put/get operations
  - Blocking and non-blocking behavior
  - Multiple producers/consumers
  - Close behavior (graceful/immediate)
  - Ring buffer wrapping
@coderabbitai

coderabbitai Bot commented Oct 4, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Refactors sync primitives to require an explicit Runtime on operations (initters become constant inits), adds a generic bounded coroutine-safe Queue(T) with blocking/try/close semantics, and updates call sites and examples (net/tcp/examples) plus README to mention Queue(T).

Changes

Cohort / File(s) Summary of Changes
Docs: Features list
README.md
Added feature bullet: Queue(T) for producer-consumer patterns across coroutines.
Sync primitives API refactor + new Queue
src/sync.zig
Removed per-instance Runtime fields; made .init constant initializers; threaded *Runtime into methods (e.g., Mutex.lock/unlock, Condition.wait/signal/broadcast, ResetEvent.set/wait/timedWait); updated internal wake/timeout paths to use provided runtime. Added pub fn Queue(comptime T: type) with bounded ring-buffer semantics, blocking/try put/get, isEmpty/isFull, close, and Queue errors (QueueClosed, QueueEmpty, QueueFull).
Call-site updates: net & tcp
src/net.zig, src/tcp.zig
Updated uses of ResetEvent and other sync ops: ResetEvent.init becomes no-arg; set, wait, and timed waits now take *Runtime argument. Adjusted readiness signaling and test usage accordingly.
Examples: mutex & producer-consumer
examples/mutex_demo.zig, examples/producer_consumer.zig
Updated examples to call mutex/condition/ResetEvent methods with rt parameter (e.g., mutex.lock(rt)), removed per-instance runtime init calls (use Mutex.init, Condition.init), and changed producer/consumer put/get to accept rt.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant P as Producer coroutine
  participant C as Consumer coroutine
  participant Q as Queue(T)
  participant RT as Runtime

  Note over Q,RT: Bounded FIFO with runtime-parameterized ops
  P->>Q: put(item, RT)
  alt queue full
    Q-->>P: suspend (put) / return QueueFull (tryPut)
    Q->>RT: park producer
  else space available
    Q-->>P: ok
  end

  C->>Q: get(RT)
  alt queue empty
    Q-->>C: suspend (get) / return QueueEmpty (tryGet)
    Q->>RT: park consumer
  else item available
    Q-->>C: item
  end

  rect rgba(230,245,255,0.5)
    Note right of Q: close(RT, immediate)\nUnblocks waiters with QueueClosed
  end
Loading
sequenceDiagram
  autonumber
  participant T as Task
  participant E as ResetEvent
  participant RT as Runtime

  Note over E,RT: ResetEvent methods now take `*Runtime`
  T->>E: wait(RT)
  par Another task
    Other->>E: set(RT)
  end
  E->>RT: wake waiting tasks
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

I nibble bytes and hop on queues,
Carrots queued for producer crews. 🥕
Lock and wait, then set — awake!
Runtime guides each sleepy break.
In bounded rings our threads amuse.

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 succinctly and accurately summarizes the core updates in this pull request by noting the refactoring of synchronization primitives and the introduction of the new generic Queue(T) API, making it clear and relevant to the changeset.
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 sync-queue-implementation

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: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 36268eb and d466d55.

📒 Files selected for processing (4)
  • README.md (1 hunks)
  • src/net.zig (6 hunks)
  • src/sync.zig (28 hunks)
  • src/tcp.zig (5 hunks)
🧰 Additional context used
🪛 GitHub Actions: CI
src/sync.zig

[error] 9-9: Mutex is defined as a struct, not a function. Ensure correct initialization (e.g., Mutex{ ... } or Mutex.init(...) if a constructor exists).

Comment thread src/sync.zig Resolved
- Removed explicit Error enum with all possible errors
- Changed get(), tryGet(), put(), tryPut() to use inferred error sets
- Each method now only declares the errors it actually returns:
  - get(): error.QueueClosed
  - tryGet(): error.QueueClosed, error.QueueEmpty
  - put(): error.QueueClosed
  - tryPut(): error.QueueClosed, error.QueueFull
@lalinsky

lalinsky commented Oct 4, 2025

Copy link
Copy Markdown
Owner Author

@claude address CI build failures

@claude

claude Bot commented Oct 4, 2025 •

Copy link
Copy Markdown

Claude finished @lalinsky's task —— View job


✅ CI Build Failures Fixed

Summary

Fixed all CI build failures by updating example files to use the refactored sync primitives API and added a zero-capacity queue guard as suggested by CodeRabbit.

Changes Made

  1. Fixed examples/mutex_demo.zig:

    • Changed zio.Mutex.init(&runtime) → zio.Mutex.init
    • Updated mutex.lock() → mutex.lock(rt) and mutex.unlock() → mutex.unlock(rt)
  2. Fixed examples/producer_consumer.zig:

    • Changed zio.Mutex.init(runtime) → zio.Mutex.init
    • Changed zio.Condition.init(runtime) → zio.Condition.init
    • Updated all method calls to pass rt parameter: lock(rt), unlock(rt), wait(rt, ...), signal(rt)
    • Updated BoundedBuffer.put() and get() signatures to accept rt: *zio.Runtime parameter
  3. Added zero-capacity queue guard (src/sync.zig:661):

    • Added std.debug.assert(buffer.len > 0) in Queue.init() to prevent division-by-zero errors

Test Results

✅ All 50 tests passed locally

  • Formatting check: ✅
  • Unit tests: 50/50 ✅
  • xev tests: ✅

Commit

  • b68e1bc - Fix example files to use new sync primitives API

The changes have been pushed to the sync-queue-implementation branch. CI should now pass! 🎉


Job Run | Branch: sync-queue-implementation

Updates example files to use the refactored sync primitives API where
Runtime must be passed as a parameter to methods. Also adds assertion
to prevent zero-capacity Queue initialization.

Changes:
- Update mutex_demo.zig to use Mutex.init constant and pass rt to lock/unlock
- Update producer_consumer.zig to use Mutex/Condition.init constants
- Pass rt parameter to all lock/unlock/wait/signal calls in examples
- Add buffer.len > 0 assertion in Queue.init() to prevent division-by-zero

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Lukáš Lalinský <[email protected]>

@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 (1)
src/sync.zig (1)

22-23: Clarify the unused runtime parameter.

The runtime parameter is accepted but immediately discarded with _ = runtime;. If the runtime is genuinely not needed for lock() (because the coroutine context is obtained via coroutines.getCurrent()), consider either:

  1. Adding a doc comment explaining why the parameter exists for API consistency
  2. Removing the parameter if it's not required

The same pattern appears in ResetEvent.wait() at line 216.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bd3a074 and b68e1bc.

📒 Files selected for processing (3)
  • examples/mutex_demo.zig (2 hunks)
  • examples/producer_consumer.zig (4 hunks)
  • src/sync.zig (28 hunks)
🔇 Additional comments (7)
examples/mutex_demo.zig (1)

11-12: LGTM! Refactoring correctly applied.

The mutex usage has been properly updated to pass the runtime parameter to lock/unlock, and initialization now uses the constant Mutex.init pattern. These changes align with the broader API refactoring described in the PR.

Also applies to: 32-32

src/sync.zig (5)

59-160: LGTM! Condition refactoring is correct.

The Condition implementation properly threads the runtime parameter through all operations. The timeout handling in timedWait correctly uses the runtime for timer operations and coroutine wake-up.


162-316: ResetEvent refactoring looks correct.

The ResetEvent implementation properly uses the runtime parameter in set() and timedWait() for coroutine management. The unused parameter in wait() was already noted in the Mutex review.


660-663: Zero-capacity assertion properly addresses previous review.

The assertion at line 661 (std.debug.assert(buffer.len > 0);) correctly guards against zero-capacity queues, addressing the previous review comment. This prevents division-by-zero issues in the ring buffer modulo operations.


640-799: Queue(T) implementation looks solid.

The bounded FIFO queue implementation is well-structured:

  • Ring buffer semantics are correctly implemented with head/tail pointers and modulo arithmetic
  • Blocking operations (get/put) properly wait on conditions and check for closure
  • Non-blocking operations (tryGet/tryPut) correctly return appropriate errors
  • Close semantics handle both graceful (drain items) and immediate (clear buffer) modes
  • Synchronization using mutex and two conditions (not_empty/not_full) follows classic producer-consumer pattern

318-1115: Excellent test coverage for both refactored and new code.

The test suite is comprehensive:

  • All existing tests for Mutex, Condition, and ResetEvent have been updated to use the new runtime-aware API
  • 9 new tests for Queue(T) cover essential scenarios: basic operations, blocking/non-blocking behavior, multiple producers/consumers, close modes, error handling, and ring buffer wrapping
  • The tests validate both happy paths and error conditions
examples/producer_consumer.zig (1)

13-21: LGTM! BoundedBuffer correctly updated for runtime-aware API.

All changes align with the synchronization primitive refactoring:

  • Initialization properly uses constant initializers (Mutex.init, Condition.init)
  • The runtime parameter is correctly marked as unused in init() since it's no longer needed
  • Method signatures updated to accept runtime parameters
  • All synchronization operations properly pass the runtime through

Also applies to: 23-41, 43-63, 69-69, 77-77

@lalinsky
lalinsky merged commit 08fceaa into main Oct 4, 2025
@lalinsky
lalinsky deleted the sync-queue-implementation branch October 23, 2025 21:01
lalinsky added a commit that referenced this pull request Jan 6, 2026
)

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.
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