为什么不Lock'i​​ng对同一个对象会导致死锁? [英] Why doesn't Lock'ing on same object cause a deadlock?

查看:204
本文介绍了为什么不Lock'i​​ng对同一个对象会导致死锁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
  在C#中 重入锁

Possible Duplicate:
Re-entrant locks in C#

如果我写了一些code是这样的:

If I write some code like this:

class Program {
    static void Main(string[] args) {
        Foo();
        Console.ReadLine();
    }

    static void Foo() {
        lock(_lock) {
            Console.WriteLine("Foo");
            Bar();
        }
    }

    static void Bar() {
        lock(_lock) {
            Console.WriteLine("Bar");
        }
    }

    private static readonly object _lock = new object();
}

我得到的输出:

I get as output:

Foo
Bar

我希望这个死锁,因为富获取一个锁,然后等待吧获取锁。但是,这种情况不会发生。

I expected this to deadlock, because Foo acquires a lock, and then waits for Bar to acquire the lock. But this doesn't happen.

是否锁紧机构干脆让这一点,因为code是在同一个线程中执行?

Does the locking mechanism simply allow this because the code is executed on the same thread?

推荐答案

有关同一个线程锁总是折返 ,因此它可以锁定对象尽可能经常就是了。

For the same thread a lock is always reentrant, so it can lock an object as often as it wants.

这篇关于为什么不Lock'i​​ng对同一个对象会导致死锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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