x86暂停指令的跨平台实现 [英] Cross-platform implementation of the x86 pause instruction

查看:119
本文介绍了x86暂停指令的跨平台实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写x86暂停指令的跨平台实现的最佳实践是什么?
我打算在C ++ 11项目的繁忙旋转循环中使用它。

What is the best practice to write a cross platform implementation of the x86 pause instruction? I am planning to use it in a busy spinning loop in a C++ 11 project.

如果我仅使用gcc工具链,则可以使用_mm_pause内在函数。即使本机处理器不支持x86暂停指令,此内在函数是否也能正确执行操作?我也希望我的代码也可以在clang / llvm工具链上工作。

If I was only using the gcc tool-chain then I could use the _mm_pause intrinsic. Does this intrinsic do the right thing even when the native processor does not support the x86 pause instruction? I would also like my code to work on the clang/llvm tool-chain too.

我认为后备可以使用 std :: this_thread :: sleep_for,因为我正在使用C ++11。但是我不确定如何检测处理器功能(支持暂停还是不支持)并退回睡眠状态。

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.

我正在使用cmake进行构建我的项目,也将始终在同一台计算机上构建和部署。所以我很乐意在编译过程中检测处理器设置。

I am using cmake to build my project and also will always build and deploy on the same machine. 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
}


推荐答案


即使本地处理器
不支持x86暂停指令,此内在函数也能正确执行吗?

Does this intrinsic do the right thing even when the native processor does not support the x86 pause instruction?

是,暂停指令被编码为F390。不知道此指令的奔腾4之前的处理器会将其解码为:

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:

  REP NOP

那只是普通的 NOP 和一个无用的前缀字节。处理器将等待一两个周期,然后继续运行而不会以任何方式更改处理器状态。使用 PAUSE 不会获得性能和功耗上的好处,但是该程序仍将按预期运行。

That is just a ordinary NOP with a useless prefix-byte. 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.

乐趣事实: REP NOP 在大约35年前发布的8086上甚至是合法的。这就是我所说的向后兼容性。

Fun fact: REP NOP was even legal on the 8086 released roughly 35 years ago. That's what I call backward compatibility.

这篇关于x86暂停指令的跨平台实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆