Spinlock vs std :: mutex :: try_lock [英] Spinlock vs std::mutex::try_lock

查看:375
本文介绍了Spinlock vs std :: mutex :: try_lock的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用特别设计的自旋锁的好处(例如 http://anki3d.org/spinlock )与这样的代码:

What are the benefits of using a specifically designed spinlock (e.g. http://anki3d.org/spinlock) vs. code like this:

std::mutex m;
while (!m.try_lock()) {}
# do work
m.unlock();


推荐答案

在典型的硬件上, p>

On typical hardware, there are massive benefits:


  1. 您的天真的假自旋锁可能会使CPU内部总线饱和,而CPU会转动,使其他物理核心

  1. Your naive "fake spinlock" may saturate internal CPU buses while the CPU spins, starving other physical cores including the physical core that holds the lock.

如果CPU支持超线程或类似的东西,那么你天真的假spinlock可能会消耗物理内核上的过多执行资源,

If the CPU supports hyper-threading or something similar, your naive "fake spinlock" may consume excessive execution resources on the physical core, starving another thread sharing that physical core.

您的天真的假自旋锁可能会执行无关的写操作,导致错误的缓存行为。当您在x86 / x86_64 CPU上执行读 - 修改 - 写操作时(像try_lock可能执行的compare / exchange),它总是写入,即使该值没有改变。此写入操作会导致高速缓存行在其他核心上失效,从而需要他们在另一个核心访问该线路时重新共享它。

Your naive "fake spinlock" probably does extraneous write operations that result in bad cache behavior. When you perform a read-modify-write operation on an x86/x86_64 CPU (like the compare/exchange that try_lock probably does), it always writes even if the value isn't changed. This write causes the cache line to be invalidated on other cores, requiring them to re-share it when another core accesses that line. This is awful if threads on other cores contend for the same lock at the same time.

您的天真的假自旋锁与分支预测的交互非常糟糕。当你终于得到锁,你把所有误预测的分支的母亲在你锁定其他线程的点,需要尽快执行。这就像一个跑步者都在抽油,准备在起跑线跑,但后来他听到起跑手枪,他停下来喘息。

Your naive "fake spinlock" interacts badly with branch prediction. When you finally do get the lock, you take the mother of all mispredicted branches right at the point where you are locking out other threads and need to execute as quickly as possible. This is like a runner being all pumped up and ready to run at the starting line but then when he hears the starting pistol, he stops to catch his breath.

基本上,该代码做的一切错误,是可能的自旋锁做错了。绝对没有做有效的。编写良好的同步原语需要深厚的硬件专业知识。

Basically, that code does everything wrong that it is possible for a spinlock to do wrong. Absolutely nothing is done efficiently. Writing good synchronization primitives requires deep hardware expertise.

这篇关于Spinlock vs std :: mutex :: try_lock的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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