Skip to content

Add ResetEvent synchronization primitive - #10

Merged
lalinsky merged 3 commits into
mainfrom
sync-event
Sep 27, 2025
Merged

lalinsky merged 3 commits into
mainfrom
sync-event

Conversation

@lalinsky

@lalinsky lalinsky commented Sep 27, 2025 •

Copy link
Copy Markdown
Owner

Summary

  • Implements zio.ResetEvent similar to std.Thread.ResetEvent but adapted for coroutine-based runtime
  • Adds atomic state management with CAS-based set() operation for thread safety
  • Implements wait queue for blocked coroutines and timeout support via xev.Timer

Features

  • Atomic state management: Uses enum-based states (unset/is_set) with u8 storage
  • Thread-safe operations: CAS in set() ensures only one winner wakes waiters
  • Coroutine integration: Proper integration with runtime's markReady/waitForReady
  • Timeout support: timedWait() method with nanosecond precision
  • Broadcast semantics: set() wakes all waiting coroutines

API

  • init(runtime) - Initialize with runtime reference
  • isSet() - Check if event is set (atomic load with acquire ordering)
  • set() - Mark event as set using CAS, wake all waiters
  • reset() - Clear the set state
  • wait() - Block until event is set
  • timedWait(timeout_ns) - Block with timeout

Test plan

  • Basic set/reset/isSet operations
  • wait() blocking and signaling between coroutines
  • timedWait() timeout scenarios
  • Multiple waiters with broadcast wake semantics
  • Edge case of waiting on already-set event
  • All tests pass with zig build test

Summary by CodeRabbit

  • New Features

    • Added a resettable event synchronization primitive for coordinating concurrent tasks. Supports set, reset, wait, and optional timeouts to avoid indefinite blocking; available via the public API for use in asynchronous workflows.
  • Chores

    • Updated project ignore rules to exclude local build and cache artifacts, reducing VCS noise and preventing accidental commits of generated files.

Implements zio.ResetEvent similar to std.Thread.ResetEvent but adapted for
coroutine-based runtime. Features atomic state management with CAS-based
set() operation, wait queue for blocked coroutines, and timeout support.

- Add ResetEvent struct with atomic state and wait queue
- Implement core methods: init, isSet, set, reset, wait, timedWait
- Use compare-and-swap in set() to ensure only winner wakes waiters
- Add comprehensive tests covering all functionality
- Export ResetEvent through main zio module
@coderabbitai

coderabbitai Bot commented Sep 27, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds .gitignore entries and introduces a public ResetEvent concurrency primitive (init, isSet, set, reset, wait, timedWait with timeout via xev timer). Re-exports ResetEvent from src/zio.zig.

Changes

Cohort / File(s) Summary
Git ignore updates
/.gitignore
Add ignore rules for /.claude, /.zig-cache, and /zig-out.
Sync primitive: ResetEvent
src/sync.zig
Add pub const ResetEvent with init(runtime), isSet(), set(), reset(), wait(), and timedWait(timeout_ns); uses an atomic state, wait queue, runtime/task integration, CAS set, wake-all semantics, and xev timer for timeouts.
Public re-exports
src/zio.zig
Re-export ResetEvent from sync.zig.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Caller
  participant RE as ResetEvent
  participant WQ as WaitQueue
  participant RT as Runtime
  participant XT as xev Timer

  rect rgba(230,240,255,0.35)
  Caller->>RE: wait()
  alt isSet fast-path
    RE-->>Caller: return
  else not set
    RE->>WQ: enqueue(caller task)
    RE->>RT: suspend(task)
    note right of RT: task parked
  end
  end

  rect rgba(235,255,235,0.35)
  Caller->>RE: set()
  RE->>RE: CAS unset -> set
  RE->>WQ: wake all waiters
  WQ->>RT: resume(waiters)
  RT-->>Caller: continue
  end
Loading
sequenceDiagram
  autonumber
  actor Caller
  participant RE as ResetEvent
  participant WQ as WaitQueue
  participant RT as Runtime
  participant XT as xev Timer

  Caller->>RE: timedWait(timeout_ns)
  alt isSet fast-path
    RE-->>Caller: return
  else not set
    RE->>WQ: enqueue(caller task)
    RE->>XT: arm timer(timeout_ns)
    RE->>RT: suspend(task)
  end

  alt Event set before timeout
    RE->>WQ: wake all
    WQ->>RT: resume(task)
    XT-->>XT: cancel timer
    RT-->>Caller: return
  else Timeout fires
    XT-->>RT: timeout for task
    RT-->>Caller: error Timeout
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

I twitch my whiskers, set and clear,
A queue of sleepers, drawing near.
Timers tick, then gently chime—
Wake the burrow, one by time.
I thump, they spring: concurrency sublime. 🐇✨

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 “Add ResetEvent synchronization primitive” directly and concisely summarizes the primary change in this PR by indicating the addition of a new ResetEvent API, making it immediately clear to reviewers what the main feature being introduced is.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch sync-event

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 47f68ab and cc326ef.

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

226-233: Close the lost wake-up race in wait().

There's still a window where set() can run after we flip the state to .waiting but before we append, observe an empty queue, and leave this coroutine parked forever. Re-check the state immediately after the append and, if the event is already set, pull the node back out (or notice that set() already dequeued us) and skip waitForReady().

         const task_node = Runtime.taskPtrFromCoroPtr(current);
         self.wait_queue.append(task_node);
 
+        if (self.isSet()) {
+            if (self.wait_queue.remove(task_node)) {
+                return;
+            }
+            return;
+        }
+
         // Suspend until woken by set()
         current.waitForReady();

259-317: Apply the same post-enqueue check in timedWait().

timedWait() keeps the same lost wake-up hole: if set() races in right after the append, it finds no waiters, signals nobody, and this coroutine stays asleep (or times out spuriously). Mirror the post-append re-check here before spinning up the timer.

         const task_node = Runtime.taskPtrFromCoroPtr(current);
 
         self.wait_queue.append(task_node);
 
+        if (self.isSet()) {
+            if (self.wait_queue.remove(task_node)) {
+                return;
+            }
+            return;
+        }
+
         // Setup timer for timeout
         var timed_out = false;
         var timer = xev.Timer.init() catch unreachable;

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: 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 b24aae8 and 47f68ab.

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

Comment thread src/sync.zig Resolved
Comment thread src/sync.zig Resolved
Implements three-state model to eliminate race between checking state
and registering as waiter. Uses atomic CAS to register waiters and
swap() in set() to atomically determine if waiters need waking.

States:
- unset (0): Event not set, no waiters
- waiting (1): Event not set, coroutines waiting
- is_set (2): Event is set

Changes:
- wait()/timedWait() use CAS unset→waiting to atomically register
- set() uses swap() to atomically set state and detect waiters
- Eliminates gap where set() can miss waiters during registration
- Adds comprehensive documentation matching std.Thread.ResetEvent
@lalinsky
lalinsky merged commit bba9399 into main Sep 27, 2025
@lalinsky
lalinsky deleted the sync-event branch September 27, 2025 19:54
lalinsky added a commit that referenced this pull request Jan 6, 2026
* Try to optimize CI

* Optimize CI workflow to reduce VM overhead

Split CI into separate build and test jobs. Build jobs cross-compile
test binaries and upload as artifacts. VM test jobs download artifacts
instead of copying entire workspace (~500MB+ including Zig installation).

This fixes NetBSD VM hangs caused by excessive file copying and speeds
up FreeBSD VM tests. VMs now only transfer ~2-5MB of test binaries.

Also consolidates multiple backend tests per platform (epoll+poll on
Linux, kqueue+poll on macOS/FreeBSD, kqueue+epoll on NetBSD).

* Remove QEMU test jobs from CI

QEMU tests for aarch64 and riscv64 are not needed for this project.

* Fix NetBSD to test kqueue and poll instead of epoll

epoll is Linux-specific and not available on NetBSD. NetBSD should
test kqueue (native) and poll (POSIX fallback).
lalinsky added a commit that referenced this pull request Jan 6, 2026
* Separate guard page check from uncommitted region in signal handler

This makes the logic clearer by explicitly distinguishing between:
- Guard page faults (true stack overflow, always abort)
- Uncommitted region faults (automatic stack growth)

* Improve stack overflow error messages with detailed diagnostics

The error message now includes:
- Fault address
- Stack base address
- Total stack size
- Currently committed size
- Whether fault was in guard page

This makes debugging stack overflow issues much easier.

* Fix exports
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