Skip to content

Improve futex implementations and refactor thread synchronization - #305

Merged
lalinsky merged 5 commits into
mainfrom
futex-improvements
Feb 8, 2026
Merged

lalinsky merged 5 commits into
mainfrom
futex-improvements

Conversation

@lalinsky

@lalinsky lalinsky commented Feb 8, 2026

Copy link
Copy Markdown
Owner

Summary

  • Rename thread_wait.zig to thread.zig and Event to Notify for clarity
  • Add EINTR retry loops to all futex wait operations across platforms
  • Add early return checks when value changes before blocking
  • Use FUTEX_PRIVATE variants on FreeBSD for better performance
  • Fix wake count types (maxInt(i32) for Linux, c_ulong for FreeBSD)
  • Add ConditionFutex: simpler futex-based condition variable using sequence counter
  • Use ConditionFutex when futex is available, ConditionNotify as fallback
  • Add tests for Mutex locking and Futex wake-all
  • Fix Condition broadcast test to handle spurious wakeups

Test plan

  • Run ./check.sh to verify all tests pass
  • Review futex implementations across platforms (Linux, Darwin, FreeBSD, OpenBSD, DragonFly)

@coderabbitai

coderabbitai Bot commented Feb 8, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

@lalinsky has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 19 minutes and 53 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.

📝 Walkthrough

Walkthrough

Refactors synchronization primitives: replaces Event with Notify across thread/os surfaces, updates Waiter fields and call sites, adjusts platform wait/timedWait/wake implementations, updates thread pool and os re-exports, and adds two FreeBSD umtx private-operation constants.

Changes

Cohort / File(s) Summary
Waiter & consumers
src/common.zig, src/completion_queue.zig
Replace event field with notify (thread_wait.Event → os.thread.Notify); update initializers and all wait/signal/timedWait call sites to use the new Notify API.
Thread primitives & platform implementations
src/os/thread.zig
Rename public surface Event → Notify and platform variants; update wait/timedWait signatures (current → expected), add loops for spurious wakeups/EINTR, and adjust wake counts/types per platform.
OS re-exports
src/os/root.zig
Switch import/export from thread_wait to thread and re-export Mutex, Condition, and ResetEvent from the new thread module.
Thread pool
src/ev/thread_pool.zig
Swap field types to use os.Mutex and os.Condition (was thread_wait.*) and update default initializers accordingly.
Platform constants
src/os/freebsd.zig, src/os/darwin.zig
Add FreeBSD private umtx constants UMTX_OP_WAIT_UINT_PRIVATE = 15, UMTX_OP_WAKE_PRIVATE = 16; adjust Darwin ULF flags (ULF_NO_ERRNO, swap wake/all/thread encodings).
Tests & docs
src/os/..., test files
Update tests and comments to reference Notify instead of Event, and adapt method names/signatures (init/wait/timedWait/signal/broadcast).

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

Poem

🔔 Event hung its hat and walked away,
Notify stepped in to call the day,
Futex and umtx now sing in tune,
Waiters wake under a steady moon,
Threads nod once — the new code hums hooray.

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately reflects the main changes: refactoring thread synchronization primitives (Event → Notify) and improving futex implementations across platforms.
Description check ✅ Passed The description is directly related to the changeset, covering the core refactoring (Event → Notify, thread_wait → thread), futex improvements, and platform-specific fixes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch futex-improvements

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/os/thread.zig (1)

189-248: ⚠️ Potential issue | 🟡 Minor

EINTR retry loops and early-return checks on Linux futex — solid improvement.

The while (true) + check-before-syscall + EINTR continue pattern is correct. The early ptr.load(.monotonic) != expected check avoids a needless syscall when the value has already changed.

One minor thing on timedWait (line 212–232): timeout_ts is computed once before the loop. Since Linux FUTEX_WAIT uses a relative timeout, an EINTR retry restarts the full timeout duration rather than the remaining time. This means the effective timeout can exceed the requested duration under repeated signal delivery. In practice this is rare, and all callers that need strict timeout semantics already use deadline-based retry loops (e.g., Waiter.timedWaitFutex, ConditionNotify.timedWait), so it's acceptable here.

🤖 Fix all issues with AI agents
In `@src/os/thread.zig`:
- Around line 1199-1229: The test "Mutex - basic lock unlock" spawns three
threads that increment an atomic counter but never asserts the final value;
because the thread joins are done with defer, the assertion would run before
threads finish. Replace the deferred joins for t1/t2/t3 with explicit calls to
t1.join(), t2.join(), t3.join() before checking the counter, then assert the
atomic counter equals 300 (use the atomic.Value load/fetch method with
appropriate memory ordering) so the test verifies correctness after
Mutex.init/lock/unlock in worker completes.

Comment thread src/os/thread.zig
Comment on lines +1199 to +1229
test "Mutex - basic lock unlock" {
if (builtin.single_threaded) return error.SkipZigTest;

var mutex = Mutex.init();
defer mutex.deinit();
var counter = std.atomic.Value(u32).init(0);

const Context = struct {
mutex: *Mutex,
counter: *std.atomic.Value(u32),
};

const worker = struct {
fn run(ctx: *Context) void {
var i: u32 = 0;
while (i < 100) : (i += 1) {
ctx.mutex.lock();
_ = ctx.counter.fetchAdd(1, .monotonic);
ctx.mutex.unlock();
}
}
}.run;

var ctx = Context{ .mutex = &mutex, .counter = &counter };
const t1 = try std.Thread.spawn(.{}, worker, .{&ctx});
const t2 = try std.Thread.spawn(.{}, worker, .{&ctx});
const t3 = try std.Thread.spawn(.{}, worker, .{&ctx});
defer t1.join();
defer t2.join();
defer t3.join();
}

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.

⚠️ Potential issue | 🟡 Minor

Test "Mutex - basic lock unlock" doesn't assert the final counter value.

Three threads each increment a counter 100 times under mutex protection, but the test never checks counter == 300. Without the assertion, this test only verifies no crash/deadlock — the existing "Mutex - contention" test (line 1448) already does the same thing plus verifies correctness. Consider adding the assertion or dropping this test in favor of the other one.

Proposed fix
     defer t1.join();
     defer t2.join();
     defer t3.join();
+
+    t1.join();
+    t2.join();
+    t3.join();
+    try std.testing.expectEqual(`@as`(u32, 300), counter.load(.acquire));
 }

Note: with defer joins, the assertion would run before joins complete. You'd need to restructure to join explicitly first.

🤖 Prompt for AI Agents
In `@src/os/thread.zig` around lines 1199 - 1229, The test "Mutex - basic lock
unlock" spawns three threads that increment an atomic counter but never asserts
the final value; because the thread joins are done with defer, the assertion
would run before threads finish. Replace the deferred joins for t1/t2/t3 with
explicit calls to t1.join(), t2.join(), t3.join() before checking the counter,
then assert the atomic counter equals 300 (use the atomic.Value load/fetch
method with appropriate memory ordering) so the test verifies correctness after
Mutex.init/lock/unlock in worker completes.

@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

🤖 Fix all issues with AI agents
In `@src/os/thread.zig`:
- Around line 1559-1569: The spurious-wakeup decrement racing with the main
thread makes threads_ready unreliable; in waiter.run (the waiter struct's run
function) stop decrementing ctx.threads_ready on a spurious wakeup—keep the
initial fetchAdd(1) as the single indicator of a thread entering the wait state,
rely on ctx.ready.load(.acquire) for re-checks, and let the main thread use
ctx.threads_ready >= N plus ctx.ready to decide when to broadcast; additionally
add an explicit assertion after the final count.fetchAdd(...) (the test’s shared
counter) that the final count equals the expected number of awakened threads to
ensure all threads actually woke.
- Around line 212-232: timedWait currently computes timeout_ts once and on EINTR
restarts the full relative timeout, so change timedWait (and the other platform
implementations named timedWait in Darwin/FreeBSD/OpenBSD/DragonFly) to use an
absolute deadline or recompute the remaining relative timeout each loop
iteration: before the loop compute a deadline = monotonic now + timeout, then on
each iteration convert (deadline - now) to a timespec and pass that to sys.futex
(or use FUTEX_WAIT_BITSET with CLOCK_MONOTONIC absolute timeout on Linux);
update the EINTR branch to continue only if remaining time > 0 and return
Timeout when the deadline is reached.
🧹 Nitpick comments (1)
src/os/thread.zig (1)

403-416: FreeBSD wake count: c_ulong variable but maxInt(c_int) value — works, but mildly inconsistent.

The _umtx_op count parameter is unsigned long on FreeBSD, so n is c_ulong. But the .all arm uses maxInt(c_int) (a signed max). It's safe — positive value fits in unsigned — but maxInt(c_ulong) would match the declared type and wake the same "everyone" semantics.

Not blocking, just a heads-up.

Comment thread src/os/thread.zig Resolved
Comment thread src/os/thread.zig Resolved
- Add EINTR retry loops to all futex wait operations
- Add early return when value changes before blocking
- Use FUTEX_PRIVATE variants on FreeBSD for better performance
- Fix wake count types (maxInt(i32) for Linux, c_ulong for FreeBSD)
- Add ConditionFutex: simpler futex-based condition variable using sequence counter
- Rename ConditionEvent to ConditionNotify for clarity
- Use ConditionFutex when futex is available, ConditionNotify as fallback
- Add tests for Mutex locking and Futex wake-all
- Fix Condition broadcast test to handle spurious wakeups
Use direct comparison 'Futex == void' instead of '@typeof(Futex) == void'
since Futex is already a type value. This ensures ConditionNotify is
correctly selected on platforms without futex support (like NetBSD).
Futex syscalls atomically check the value and handle spurious wakeups
correctly. There's no need for pre-checks or EINTR retry loops - just
call the syscall and return. Spurious wakeups are handled by callers.

This simplifies all implementations:
- Linux: Remove while loop and pre-check
- FreeBSD: Remove while loop and pre-check
- OpenBSD: Remove while loop and pre-check
- DragonFly: Remove while loop and pre-check
- Darwin: Already simplified in previous commits

Only keep ETIMEDOUT check in timedWait to return error.Timeout.
@lalinsky
lalinsky merged commit ad1557e into main Feb 8, 2026
14 checks passed
@lalinsky
lalinsky deleted the futex-improvements branch February 8, 2026 21:50
@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