锁aqcuired并进一步尝试锁定不阻止:在C#锁重入? [英] Lock aqcuired and further attempts to lock do not block: are C# locks re-entrant?

查看:276
本文介绍了锁aqcuired并进一步尝试锁定不阻止:在C#锁重入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写了什么,我觉得应该是一个僵局有效的情况下进行测试。看来,一旦锁定已获得了一个类的实例,该实例并不需要重新获得锁定了,即使我明确地尝试,应该锁定再调用另一个方法。

I've written a test of what I think should be a valid case for a deadlock. It appears that once the lock has been acquired by an instance of the a class, that instance doesn't need to re-acquire the lock anymore even if I explicitly try to call another method that should lock again.

下面是类:

internal class Tester
{
    private readonly object _sync = new object();

    public Tester() { }

    public void TestLock()
    {
        lock (_sync)
        {
            for (int i = 0; i < 10; i++)
            {
                Deadlock(i);
            }
        }

    }

    private void Deadlock(int i)
    {
        lock (_sync)
        {
            Trace.WriteLine(i + " no deadlock!");
        }
    }
}

输出:

0无僵局!
  1没有僵局!
  2没有僵局!
  3没有僵局!
  4没有僵局!
  5没有僵局!
  6没有僵局!
  7没有僵局!
  8没有僵局!
  9没有僵局!

0 no deadlock!
1 no deadlock!
2 no deadlock!
3 no deadlock!
4 no deadlock!
5 no deadlock!
6 no deadlock!
7 no deadlock!
8 no deadlock!
9 no deadlock!

我本来以为,这将导致死锁......有谁能够阐明一些这?

I would have thought that this would cause a deadlock... can anybody shed some light on this?

推荐答案

在.NET锁是可重入。从其它线程只收购被阻止。当同一线程锁定该同一对象多次,它简单地递增的计数器,并且当释放时它递减。当计数器降为零,这个锁是实际发布从其他线程访问。

Locks in .NET are reentrant. Only acquisitions from other threads are blocked. When the same thread locks the same object multiple times, it simply increments a counter, and decrements it when released. When the counter hits zero, the lock is actually released for access from other threads.

这篇关于锁aqcuired并进一步尝试锁定不阻止:在C#锁重入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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