Why doesn't Lock'ing on same object cause a deadlock? [duplicate]

主宰稳场 提交于 2019-12-18 11:37:52

问题


Possible Duplicate:
Re-entrant locks in C#

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.

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


回答1:


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




回答2:


Because you have only one thread here.

lock is shortcut for

bool lockWasTaken = false;
var temp = obj;
try { 
       Monitor.Enter(temp, ref lockWasTaken); 
       // your thread safe code
}
finally { if (lockWasTaken) Monitor.Exit(temp); }

Monitor.Enter acquire the Monitor on the object passed as the parameter. If another thread has executed an Enter on the object but has not yet executed the corresponding Exit, the current thread will block until the other thread releases the object. It is legal for the same thread to invoke Enter more than once without it blocking; however, an equal number of Exit calls must be invoked before other threads waiting on the object will unblock.




回答3:


One word: Reentrant lock. If a thread has already acquired a lock, then it does not wait if it wants to acquire the lock again. This is very much needed otherwise it could have turned simple recursive functions into a nightmare.!




回答4:


The lock statement is smarter than that, and it is designed to prevent just this. The lock is "owned" by the thread once it gets inside of it, so anytime it reaches another lock statement that locks on the same object it will realize that it already has access to that lock.



来源:https://stackoverflow.com/questions/13017282/why-doesnt-locking-on-same-object-cause-a-deadlock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!