“自旋锁"到底是什么? [英] What exactly are "spin-locks"?

查看:142
本文介绍了“自旋锁"到底是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我总是想知道它们是什么:每次我听到它们的声音时,类似飞轮的未来派设备的图像就会在我的脑海中跳舞(滚动?).

他们是什么?

解决方案

当您使用常规锁(互斥锁,关键节等)时,操作系统会将您的线程置于WAIT状态,并且量子并在锁定后立即继续被释放.自旋锁的简单机制允许内核在几乎任何状态下使用它.

这就是为什么在单核计算机上自旋锁只是一个禁用中断"的原因.或提高IRQL";这样会完全阻止线程调度.

自旋锁最终允许内核避免大内核锁"(当内核进入内核并在出口释放时获得的锁),并且对内核基元进行了粒度锁定,从而在多核机器上实现了更好的多处理,因此更好性能.

编辑:出现了一个问题:这是否意味着我应该尽可能使用自旋锁?"我会尽力回答:

正如我提到的那样,自旋锁仅在预期的等待时间短于量子(读取:毫秒)且抢占没有太大意义(例如内核对象不可用)的地方有用.

如果等待时间未知,或者您处于用户模式,则自旋锁效率不高.在检查自旋锁是否可用时,您在等待的内核上消耗了100%的CPU时间.您可以阻止其他线程在该核心上运行,直到您的数量到期为止.这种情况仅适用于内核级别的短脉冲,而不太可能是用户模式应用程序的选择.

这里有一个关于SO解决的问题:自旋锁,它们有多有用?

I always wondered what they are: every time I hear about them, images of futuristic flywheel-like devices go dancing (rolling?) through my mind...

What are they?

解决方案

When you use regular locks (mutexes, critical sections etc), operating system puts your thread in the WAIT state and preempts it by scheduling other threads on the same core. This has a performance penalty if the wait time is really short, because your thread now has to wait for a preemption to receive CPU time again.

Besides, kernel objects are not available in every state of the kernel, such as in an interrupt handler or when paging is not available etc.

Spinlocks don't cause preemption but wait in a loop ("spin") till the other core releases the lock. This prevents the thread from losing its quantum and continue as soon as the lock gets released. The simple mechanism of spinlocks allows a kernel to utilize it in almost any state.

That's why on a single core machine a spinlock is simply a "disable interrupts" or "raise IRQL" which prevents thread scheduling completely.

Spinlocks ultimately allow kernels to avoid "Big Kernel Lock"s (a lock acquired when core enters kernel and released at the exit) and have granular locking over kernel primitives, causing better multi-processing on multi-core machines thus better performance.

EDIT: A question came up: "Does that mean I should use spinlocks wherever possible?" and I'll try to answer it:

As I mentioned, Spinlocks are only useful in places where anticipated waiting time is shorter than a quantum (read: milliseconds) and preemption doesn't make much sense (e.g. kernel objects aren't available).

If waiting time is unknown, or if you're in user mode Spinlocks aren't efficient. You consume 100% CPU time on the waiting core while checking if a spinlock is available. You prevent other threads from running on that core till your quantum expires. This scenario is only feasible for short bursts at kernel level and unlikely an option for a user-mode application.

Here is a question on SO addressing that: Spinlocks, How Useful Are They?

这篇关于“自旋锁"到底是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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