x86 暂停指令如何在自旋锁中工作 * 和 * 是否可以用于其他场景? [英] How does x86 pause instruction work in spinlock *and* can it be used in other scenarios?

查看:32
本文介绍了x86 暂停指令如何在自旋锁中工作 * 和 * 是否可以用于其他场景?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

pause 指令通常用于测试循环spinlock,当其他一些线程拥有自旋锁时,以减轻紧密循环.据说相当于一些NOP指令.有人能告诉我它究竟是如何用于自旋锁优化的吗?在我看来,即使是 NOP 指令也是浪费 CPU 时间.它们会降低 CPU 使用率吗?

The pause instruction is commonly used in the loop of testing spinlock, when some other thread owns the spinlock, to mitigate the tight loop. It's said that it is equivalent to some NOP instructions. Could somebody tell me how exactly it works for spinlock optimization? It seems to me that even the NOP instructions are a waste of CPU time. Will they decrease CPU usage?

另一个问题是我是否可以将暂停指令用于其他类似目的.例如,我有一个繁忙的线程,它不断扫描某些地方(例如队列)以检索新节点;然而,有时队列是空的,线程只是在浪费 CPU 时间.休眠线程并由其他线程唤醒它可能是一种选择,但是线程很关键,所以我不想让它休眠.

Another question is that could I use pause instruction for other similar purposes. For example, I have a busy thread which keeps scanning some places (e.g. a queue) to retrieve new nodes; however, sometimes the queue is empty and the thread is just wasting cpu time. Sleep the thread and wake it up by other threads may be an option, however the thread is critical, so I don't want to make it sleep.

暂停指令可以用于我的目的以减轻 CPU 使用率吗?目前它使用 100% 物理核心的 cpu?

Could pause instruction work for my purpose to mitigate the CPU usage? Currently it uses 100% cpu of a physical core?

推荐答案

PAUSE 通知 CPU这是一个自旋锁等待循环,因此可以优化内存和缓存访问.另请参阅在 x86 中暂停指令,了解有关在以下情况下避免内存顺序错误推测的更多详细信息离开自旋循环.

PAUSE notifies the CPU that this is a spinlock wait loop so memory and cache accesses may be optimized. See also pause instruction in x86 for some more details about avoiding the memory-order mis-speculation when leaving the spin-loop.

PAUSE 实际上可能会停止 CPU 一段时间以节省电量.较旧的 CPU 将其解码为 REP NOP,因此您无需检查其是否受支持.较旧的 CPU 将尽可能快地什么都不做 (NOP).

PAUSE may actually stop CPU for some time to save power. Older CPUs decode it as REP NOP, so you don't have to check if its supported. Older CPUs will simply do nothing (NOP) as fast as possible.

另见 https://software.intel.com/en-us/articles/benefit-power-and-performance-sleep-loops

更新:我认为在队列检查中使用 PAUSE 不是一个好主意,除非您打算使队列类似于自旋锁(并且没有明显的方法).

Update: I don't think it's a good idea to use PAUSE in queue checking unless you are going to make your queue spinlock-like (and there is no obvious way to do it).

旋转很长时间仍然很糟糕,即使有 PAUSE.

Spinning for a very long time is still very bad, even with PAUSE.

这篇关于x86 暂停指令如何在自旋锁中工作 * 和 * 是否可以用于其他场景?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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