什么类型的锁定机制不锁定语句中使用 [英] What type of locking mechanism does lock statement use

查看:250
本文介绍了什么类型的锁定机制不锁定语句中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请问C#lock关键字使用'收益','自旋锁或混合方式来处理争?

Does the c# lock keyword use a 'yielding', 'spin-locking' or hybrid approach to handle contention?

到目前为止,我在.NET lock语句搜索尚未打开了一个答案。 我会后,如果我找到了。 到目前为止,所有我能找到的是<一个href="http://stackoverflow.com/questions/5869825/when-should-one-use-a-spinlock-instead-of-mutex">When应该使用一个自旋锁...... 与Mecki一个很好的措辞接受的答案。

So far my searches on the .net lock statement hasn't turned up an answer. I will post if I do find any more. So far all I could find is When should one use a spinlock ... with a nicely worded accepted answer by Mecki.

不过,我在找一些明确的答案或文档中关于.NET / C#,如果任何人有一个。

But I am looking for some definitive answer or documentation regarding .net/c# if anyone has one.

推荐答案

随着code:

lock (_syncRoot)
{
    // Do stuff
}

时的翻译编译器:

Is translated by the compiler to:

Monitor.Enter(_syncRoot)
try
{
    // Do stuff
}
finally
{
    Monitor.Exit(_syncRoot);
}

这是天真的(老)的实施,实际上与.NET 4.0的实现是多了还是少了这个(见的 Eric的博客获得完整的参考):

This is the naive (and old) implementation, actually with .NET 4.0 the implementation is more or less this (see Eric's blog for complete reference):

bool locked = false;
try
{
    Monitor.Enter(_syncRoot, ref locked);
}
finally
{
    if (locked)
        Monitor.Exit(_syncRoot);
}

EDITED

不过,问题是如何 Monitor.Enter()作品?的嘛,默认的单声道实现使用信号来获取锁,但微软.NET实现的行为不同。

That said the question is how Monitor.Enter() works? Well, default Mono implementation uses a semaphore to acquire the lock but Microsoft .NET implementation acts different.

我读的并发Windows程序设计的(乔·达菲),当一个段落都吸引我的注意力,我的第一个回答说:不,它不使用纺纱,因为性能可能不是一般的好案件。正确的答案是是的,.NET 显示器采用旋转。这两个.NET 显示器和Windows临界区一个内核对象回落到一个真正的等待之前执行短纺。这种算法被称为两阶段锁定协议,这是恰当的,因为上下文切换和内核转换是非常广阔的,在多处理器机器纺纱能避免他们两个。

I was reading Concurrent Windows Programming (by Joe Duffy) when a paragraph did catch my attention, my first answer said "no, it doesn't use spinning because performance may not be good in general cases". Correct answer is "yes, .NET Monitor uses spinning". Both .NET Monitor and Windows Critical Sections perform a short spinning before falling back to a true wait on a kernel object. This algorithm is called "two-phase locking protocol" and it's appropriate because context switches and kernel transitions are very expansive, on a multiprocessor machine spinning can avoid both of them.

此外,不要忘记这些是实现细节,并可以在任何版本改变(或算法可以是因为JIT编译器不同的硬件不同)。

Moreover do not forget these are implementation details and can change in any release (or algorithm can be different for different hardwares because of JIT compiler).

这篇关于什么类型的锁定机制不锁定语句中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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