简体   繁体   English

跨平台实现x86暂停指令

[英]Cross-platform implementation of the x86 pause instruction

What is the best practice to write a cross platform implementation of the x86 pause instruction? 编写x86暂停指令的跨平台实现的最佳实践是什么? I am planning to use it in a busy spinning loop in a C++ 11 project. 我打算在C ++ 11项目的繁忙旋转循环中使用它。

If I was only using the gcc tool-chain then I could use the _mm_pause intrinsic. 如果我只使用gcc工具链,那么我可以使用_mm_pause内在函数。 Does this intrinsic do the right thing even when the native processor does not support the x86 pause instruction? 即使本机处理器不支持x86暂停指令,这种内在功能是否正确? I would also like my code to work on the clang/llvm tool-chain too. 我也希望我的代码也能用于clang / llvm工具链。

I imagine that a fallback could use "std::this_thread::sleep_for" since I am using C++ 11. But I am not sure how to detect processor capability (supports pause vs does not) and fall back to sleep. 我认为回退可以使用“std :: this_thread :: sleep_for”,因为我使用的是C ++ 11.但我不确定如何检测处理器功能(支持暂停与不支持)并重新进入休眠状态。

I am using cmake to build my project and also will always build and deploy on the same machine. 我正在使用cmake来构建我的项目,并且也将始终在同一台机器上构建和部署。 So I am comfortable detecting processor settings during compilation. 所以我很乐意在编译期间检测处理器设置。

An example implementation (pseudocode) is : 示例实现(伪代码)是:

void pause() {
// Not sure how to detect if pause is available on the platform.
#if defined(USE_mm_pause)
  __asm__ ( "pause;" );
#else
  std::this_thread::sleep_for(std::chrono::seconds(0));
#endif
}

Does this intrinsic do the right thing even when the native processor does not support the x86 pause instruction? 即使本机处理器不支持x86暂停指令,这种内在功能是否正确?

Yes, the pause instruction is encoded as F3 90. A pre Pentium 4 processor which does not know about this instruction will decode it as: 是的,暂停指令编码为F3 90.不知道该指令的Pentium 4前处理器会将其解码为:

  REP NOP

That is just a ordinary NOP with a useless prefix-byte. 这只是一个普通的NOP ,带有无用的前缀字节。 The processor will wait a cycle or two and then continue without altering the processor state in any way. 处理器将等待一两个周期,然后继续而不以任何方式改变处理器状态。 You will not get the performance and power benefits from using PAUSE but the program will still work as expected. 使用PAUSE不会获得性能和功耗,但程序仍将按预期工作。

Fun fact: REP NOP was even legal on the 8086 released roughly 35 years ago. 有趣的事实: REP NOP在大约35年前发布的8086上甚至是合法的。 That's what I call backward compatibility. 这就是我所说的向后兼容性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM