PAUSE instruction

Is there a way to emit a PAUSE instruction (or the platform's equivalent) to support spin locks?
I found an old thread (Pre-RFC: Introducing `std::thread::pause` - libs - Rust Internals) which appears to be dead, but nothing more recent

Are you looking for yield_now?

Thanks for the fast reply!
yield_now() appears to interact with the OS to give up the rest of the thread's current time slice for other threads. What I am looking for is more fine grained - there are machine instructions (e.g. PAUSE on x86) that serves as a hint to the processor that "this is a spin loop" and allows them to optimize accordingly (see e.g. Shroud: x86 Instruction Set Reference for details).
This is for spin loops that can be short lived, where the latency introduced by giving up the thread's time slice would be way bigger than the typical spin duration.

1 Like

The crossbeam crate might have something like what you want.

You could also try something like this:

#![feature(asm)]

#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
#[inline(always)]
fn pause() {
    unsafe {
        asm!("PAUSE");
    }
}

Unfortunately this is unstable and requires a nightly compiler.

3 Likes

Ah, right, there's also this.

11 Likes

Excellent, that seems to be exactly what I was looking for. Thanks a lot for pointing it out!

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.