自旋锁的底层是如何实现的?
这是一个可以被持有的锁 只有一个执行线程 时间。尝试获取锁 由另一个执行线程使得 后者循环直到锁定 已发布。
当两个线程尝试完全相同的时间获取锁时,它如何处理这种情况?
我认为这个问题也适用于各种其他互斥体实现。
This is a lock that can be held by
only one thread of execution at a
time. An attempt to acquire the lock
by another thread of execution makes
the latter loop until the lock is
released.
How does it handle the case when two threads try to acquire the lock exactly the same time?
I think this question also applies to various of other mutex implementation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如前一张海报所示,每种现代机器类型都有一类特殊的指令,称为“原子”,它们确实按照前一张海报所示进行操作……它们至少针对指定的内存位置序列化执行。
在 x86 上,有一个 LOCK 汇编器前缀,指示机器应以原子方式处理下一条指令。当遇到该指令时,x86 上实际上会发生一些事情。
对于x86,有两个常用的指令用于实现锁。
所以,你可以像这样实现一个锁:
我们自旋,等待锁,因此,自旋锁。
现在,解锁的指令不会表现出这些良好的行为。根据您使用的机器,使用未锁定的指令,可以观察到各种违反一致性的情况。例如,即使在具有非常友好的内存一致性模型的 x86 上,也可以观察到以下情况:
在该程序结束时,y 和 z 都可以具有值 0!。
无论如何,最后一点:x86 上的 LOCK 可以应用于 ADD、OR 和 AND,以便为指令获得一致的原子读-修改-写语义。这对于设置标志变量并确保它们不会丢失很重要。如果没有这个,你就会遇到这个问题:
在这个程序结束时,x 的可能值为 1、2 和 0x1|0x2 (3)。为了获得正确的程序,您需要:
希望这会有所帮助。
As the previous poster indicates, every modern machine type has a special class of instruction known as 'atomics' that do operate as the previous poster indicates... they serialize execution against at least the specified memory location.
On x86, there is a LOCK assembler prefix that indicates to the machine that the next instruction should be handled atomically. When the instruction is encountered, several things effectively happen on x86.
For x86, there are two commonly used instructions that are used to implement locks.
So, you can implement a lock like this:
We spin, waiting for the lock, hence, spinlock.
Now, unlocked instructions don't exhibit these nice behaviors. Depending on what machine you're on, with unlocked instructions, all sorts of violations of consistency can be observed. For example, even on x86, which has a very friendly memory consistency model, the following could be observed:
At the end of this program, y and z can both have the value 0!.
Anyway, one last note: LOCK on x86 can be applied to ADD, OR, and AND, in order to get consistent and atomic read-modify-write semantics for the instruction. This is important for, say, setting flag variables and making sure they don't get lost. Without that, you have this problem:
At the end of this program, possible values for x are 1, 2, and 0x1|0x2 (3). In order to get a correct program, you need:
Hope this helps.
取决于处理器和线程实现。大多数处理器都具有可以原子执行的指令,您可以在其之上构建诸如自旋锁之类的东西。例如,IA-32 有一个执行原子交换的
xchg
指令。然后你可以实现一个简单的自旋锁,例如:Depends on the processor and the threading implementation. Most processors have instructions that can be executed atomically, on top of which you can build things like spin locks. For example IA-32 has an
xchg
instruction that does an atomic swap. You can then implement a naive spinlock like: