Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minimum time a thread can pause in Linux

In my application, threads need to pause for a very little time (100s of clock cycles). One way to pause is to call nanosleep, but I suppose it requires a system call to the kernel. Now I want to pause without going to the kernel.

Note that I have enough cores to run my threads on and I bind each thread to a separate core, so even an instruction that can halt the core for a little while would be good. I am using x86. I just want the thread to halt while pausing. I don't want a busy loop or a system call to the kernel. Is it possible to do this? What is the minimum time I can pause a thread?

like image 377
MetallicPriest Avatar asked Sep 10 '11 13:09

MetallicPriest


1 Answers

_mm_pause in a busy-wait loop is the way to go.

Unfortunately the delay it provides can change with each processor family:

http://siyobik.info/main/reference/instruction/PAUSE

Example usage for GCC on Linux:

#include <xmmintrin.h>

int main (void) {
    _mm_pause();
    return 0;
}

Compile with MMX enabled:

gcc -o moo moo.c  -march=native

Also you can always just use inline assembler:

__asm volatile ("pause" ::: "memory");

From some Intel engineers, you might find this useful to determine the cost of pausing:

NOP instruction can be between 0.4-0.5 clocks and PAUSE instruction can consume 38-40 clocks.

http://software.intel.com/en-us/forums/showthread.php?t=48371

like image 166
Steve-o Avatar answered Sep 29 '22 09:09

Steve-o