Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does asm("pause") do and why to use it

I saw asm("pause") in other people's code and I wonder what it does. The code is compiled by g++ on Linux.

This line is in a loop that's in another thread, which constantly polls if an update happens. I suspect it makes the program pauses a bit before polling again, but I wonder (1) Is my guess correct (2) why is it necessary to pause? The machine we run the code on has many processors and I the thread would totally just keep polling it.

like image 592
CuriousMind Avatar asked Apr 15 '12 05:04

CuriousMind


People also ask

What is the purpose of pause in the ASM instruction part?

See Jeff Preshing's Memory Ordering at Compile Time article. Making the asm instruction part non-empty also means those asm instructions will run every time the C logically runs that source line (because it's volatile ). pause prevents speculative loads from causing memory-ordering mis-speculation pipeling clears (aka machine nukes).

What is the purpose of non-empty instructions in ASM?

Making the asm instruction part non-empty also means those asm instructions will run every time the C logically runs that source line (because it's volatile ). pause prevents speculative loads from causing memory-ordering mis-speculation pipeling clears (aka machine nukes).

What does pause () do in C++?

pause prevents speculative loads from causing memory-ordering mis-speculation pipeling clears (aka machine nukes). It's useful inside spin loops that are waiting to see a value in memory. You might find this statement inside a spinloop written without C++11 std::atomic, to tell the compiler it has to re-read the value of a global variable.


1 Answers

Basically that is called a spin loop, or busy wait. It would consume as much CPU resources as it can. This wastes CPU processing power and increases power consumption.

By putting pause instruction, you're hinting the processor that "this is a spin loop." This forces the processor not to be too smart to make unnecessary predictions (optimizations). Also, it frees up CPU time to be used for other things in some cases (e.g. Hyperthreading).

like image 170
touko Avatar answered Sep 28 '22 03:09

touko