From 14830bfd0c8ed9fadb8bb31ff4c654810138664e Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sun, 30 Nov 2025 12:58:01 +0100 Subject: [PATCH] ThreadId generation fallback path: avoid spurious yields --- library/std/src/thread/id.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/library/std/src/thread/id.rs b/library/std/src/thread/id.rs index ba7024327881b..3da0825db604d 100644 --- a/library/std/src/thread/id.rs +++ b/library/std/src/thread/id.rs @@ -70,7 +70,9 @@ impl ThreadId { // Acquire lock. let mut spin = 0; - while COUNTER_LOCKED.compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed).is_err() { + // Miri doesn't like it when we yield here as it interferes with deterministically + // scheduling threads, so avoid `compare_exchange_weak` to avoid spurious yields. + while COUNTER_LOCKED.swap(true, Ordering::Acquire) { if spin <= 3 { for _ in 0..(1 << spin) { spin_loop(); @@ -80,6 +82,7 @@ impl ThreadId { } spin += 1; } + // This was `false` before the swap, so we got the lock. // SAFETY: we have an exclusive lock on the counter. unsafe {