为什么要使用双重锁定? [英] Why Double-Checked Locking is used at all?
问题描述
我继续运行使用双重检查锁定的代码,我仍然对它为什么会被使用感到困惑。
I keep on running across code that uses double-checked locking, and I'm still confused as to why it's used at all.
我最初没有知道双重检查锁定已被破坏,当我得知它,它为我放大了这个问题:为什么人们首先使用它?是不是比较和交换更好?
I initially didn't know that double-checked locking is broken, and when I learned it, it magnified this question for me: why do people use it in the first place? Isn't compare-and-swap better?
if (field == null)
Interlocked.CompareExchange(ref field, newValue, null);
return field;
(我的问题同时适用于C#和Java,尽管上面的代码适用于C#。)
(My question applies to both C# and Java, although the code above is for C#.)
与原子操作相比,双重检查锁定是否具有某种固有优势?
Does double-checked locking have some sort of inherent advantage compared to atomic operations?
推荐答案
好吧,我想到的唯一的优势是(幻觉)性能:以非线程安全的方式检查,然后执行一些锁定操作来检查变量,可能很贵。然而,由于双重检查的锁定方式被打破,从而排除了非线程安全检查的任何确定结论,并且它总是对我过早优化,我会声称不,没有优势 - 它是一个过时的预Java-days习惯用语 - 但是希望得到纠正。
Well, the only advantage that comes to my mind is (the illusion of) performance: check in a non-thread-safe way, then do some locking operations to check the variable, which may be expensive. However, since double checked locking is broken in a way that precludes any firm conclusions from the non-thread-safe check, and it always smacked of premature optimization to me anyway, I would claim no, no advantage - it is an outdated pre-Java-days idiom - but would love to be corrected.
编辑:要清楚(呃),我相信双重检查锁定是一种演变为性能增强的习语在每次锁定和检查时,大致与非封装的比较和交换接近。我个人也是封装代码的同步部分的粉丝,所以我认为调用另一个操作来做脏工作更好。
to be clear(er), I believe double checked locking is an idiom that evolved as a performance enhancement on locking and checking every time, and, roughly, is close to the same thing as a non-encapsulated compare-and-swap. I'm personally also a fan of encapsulating synchronized sections of code, though, so I think calling another operation to do the dirty work is better.
这篇关于为什么要使用双重锁定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!