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?
There is no such thing.
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.
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.
For the same thread a lock is always reentrant, so the thread can lock an object as often as it wants.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With