锁定锁与非锁定锁 [英] Blocking Locks versus Non-Blocking Locks

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

问题描述

我在这里思考:如果您有2个线程执行需要同步的FAST操作,那么非阻塞方法不是比阻塞/上下文切换方法更快/更好的方法吗?

I am thinking here: If you have 2 threads executing FAST operations that need to be synchronized, isn't a nonblocking approach faster/better than a blocking/context switch approach?

非阻塞性的意思是:

while(true){ 如果(checkAndGetTheLock())中断; }

while(true) { if (checkAndGetTheLock()) break; }

如果您有太多线程在锁中循环,我唯一想到的就是饥饿(CPU耗尽).

The only thing I can think of is starvation (with CPU burn out) if you have too many threads looping around the lock.

如何在一种方法与另一种方法之间取得平衡?

How do I balance one approach versus the other?

推荐答案

这是实践中的Java并发关于该主题的内容:

Here's what Java Concurrency in Practice says about the subject:

JVM可以通过旋转等待来实现阻塞(重复 尝试获取锁直到成功为止)或通过暂停 通过操作系统阻止线程.哪个更有效 取决于上下文切换开销与 直到锁可用的时间;最好等待等待 短暂的等待和暂停对于长时间的等待是可取的.一些JVM 根据过去等待的分析数据自适应地在两者之间进行选择 次,但大多数情况下只是暂停线程以等待锁定.

The JVM can implement blocking either via spin-waiting (repeatedly trying to acquire the lock until it succeeds) or bysuspending the blocked thread through the operating system. Which is more efficient depends on the relationship between context switch overhead and the time until the lock becomes available; spin-waiting is preferable for short waits and suspension is preferable for long waits. Some JVMs choose between the two adaptively based on profiling data of past wait times, but most just suspend threads waiting for a lock.

还有(这是IMO最重要的一点):

And also (which is, IMO, the most important point):

不必过分担心无竞争的同步的代价. 基本机制已经相当快,并且JVM可以执行 进一步降低或消除成本的其他优化. 相反,应将优化工作集中在锁争用的区域上 实际发生.

Don't worry excessively about the cost of uncontended synchronization. The basic mechanism is already quite fast, and JVMs can perform additional optimizations that further reduce or eliminate the cost. Instead, focus optimization efforts on areas where lock contention actually occurs.

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

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