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 (https://internals.rust-lang.org/t/pre-rfc-introducing-std-thread-pause/2469) 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. https://c9x.me/x86/html/file_module_x86_id_232.html 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.

10 Likes

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

1 Like