Repository navigation
Improve futex implementations and refactor thread synchronization - #305
Conversation
|
Warning Rate limit exceeded
⌛ 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. 📝 WalkthroughWalkthroughRefactors 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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ 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 |
There was a problem hiding this comment.
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 | 🟡 MinorEINTR retry loops and early-return checks on Linux futex — solid improvement.
The
while (true)+ check-before-syscall + EINTR continue pattern is correct. The earlyptr.load(.monotonic) != expectedcheck avoids a needless syscall when the value has already changed.One minor thing on
timedWait(line 212–232):timeout_tsis computed once before the loop. Since LinuxFUTEX_WAITuses 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.
| 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(); | ||
| } |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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_ulongvariable butmaxInt(c_int)value — works, but mildly inconsistent.The
_umtx_opcount parameter isunsigned longon FreeBSD, sonisc_ulong. But the.allarm usesmaxInt(c_int)(a signed max). It's safe — positive value fits in unsigned — butmaxInt(c_ulong)would match the declared type and wake the same "everyone" semantics.Not blocking, just a heads-up.
- 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).
16f8306 to
b2d49ec
Compare
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.
Summary
thread_wait.zigtothread.zigandEventtoNotifyfor clarityConditionFutex: simpler futex-based condition variable using sequence counterConditionFutexwhen futex is available,ConditionNotifyas fallbackTest plan
./check.shto verify all tests pass