自旋锁vs忙等待 [英] Spinlock vs Busy wait

查看:623
本文介绍了自旋锁vs忙等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请解释为什么忙碌等待通常不被接受,而旋转通常被认为是可以的.据我所知,它们都无限循环直到满足某些条件.

Please explain why Busy Waiting is generally frowned upon whereas Spinning is often seen as okay. As far as I can tell, they both loop infinitely until some condition is met.

推荐答案

自旋锁通常在资源争用较少的情况下使用,因此CPU在此之前只会进行几次迭代它可以继续进行富有成效的工作.但是,锁定功能的库实现通常使用自旋锁,后跟常规锁.如果无法在合理的时间范围内获取资源,则使用常规锁定.这样做是为了减少通常可快速获得锁的设置中上下文切换的开销.

A spin-lock is usually used when there is low contention for the resource and the CPU will therefore only make a few iterations before it can move on to do productive work. However, library implementations of locking functionality often use a spin-lock followed by a regular lock. The regular lock is used if the resource cannot be acquired in a reasonable time-frame. This is done to reduce the overhead with context switches in settings where locks usually are quickly obtained.

术语繁忙等待往往意味着您愿意旋转并等待硬件寄存器或内存位置的更改.该术语并不一定意味着锁定,但它确实意味着要在一个紧密的循环中等待,反复探测更改.

The term busy-waiting tends to mean that you are willing to spin and wait for a change in a hardware register or a memory location. The term does not necessarily mean locking, but it does imply waiting in a tight loop, repeatedly probing for a change.

您可能要使用繁忙等待,以便检测要立即响应的环境中的某种变化.因此,使用繁忙等待来实现自旋锁.在等待时间非常短的响应比浪费CPU周期更为重要的任何情况下(例如在某些类型的嵌入式编程中),忙等待都是有用的.

You may want to use busy-waiting in order to detect some kind of change in the environment that you want to respond to immediately. So a spin-lock is implemented using busy-waiting. Busy-waiting is useful in any situation where a very low latency response is more important than wasting CPU cycles (like in some types of embedded programming).

与此相关的是术语无锁"和无等待":

Related to this are the terms «lock-free» and «wait-free»:

所谓的无锁算法通常使用紧密的繁忙等待,而 CAS 指令,但是在通常情况下竞争很低,因此CPU通常只需要迭代几次.

So-called lock-free algorithms tend to use tight busy-waiting with a CAS instruction, but the contention is in ordinary situations so low that the CPU usually have to iterate only a few times.

所谓的无等待算法根本不执行任何繁忙的等待.

So-called wait-free algorithms don't do any busy-waiting at all.

(请注意,在学术环境中,无锁"和无等待"的用法略有不同,请参见Wikipedia在

(Please note that «lock-free» and «wait-free» is used slightly differently in academic contexts, see Wikipedia's article on Non-blocking algorithms.)

这篇关于自旋锁vs忙等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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