Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 463
Eric Avatar asked Oct 22 '12 18:10

Eric


People also ask

Can two threads acquire the same lock?

There is no such thing.

What is lock in multithreading?

A lock may be a tool for controlling access to a shared resource by multiple threads. Commonly, a lock provides exclusive access to a shared resource: just one thread at a time can acquire the lock and everyone accesses to the shared resource requires that the lock be acquired first.

What is nested lock?

Nested Locking. A thread can repeatedly lock the same object, either via multiple calls to Monitor.Enter, or via nested lock statements. The object is then unlocked when a corresponding number of Monitor.Exit statements have executed, or the outermost lock statement has exited.


1 Answers

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

like image 122
thumbmunkeys Avatar answered Sep 20 '22 15:09

thumbmunkeys