class Program
{
static object test = new object();
static void Main(string[] args)
{
new Program().test2();
Console.ReadKey();
}
public void test1()
{
lock (test)
{
Console.WriteLine("test1");
}
}
public void test2()
{
lock (test)
{
test1();
Console.WriteLine("test2");
}
}
}
Is the code above supposed to first finish statements in lock statement of test2() then go to the test1()?
(i.e. Doesn’t the output supposed to be like this? :
test2
test1
)
A monitor is re-entrant on the same thread. Pretty important to avoid accidental dead-lock, your code would freeze solidly if it didn’t have that behavior.
A Mutex is also re-entrant, a Semaphore is not.
The implementation is pretty straight forward. A Monitor stores two pieces of information. The owner Thread.ManagedId of the thread that entered it and a counter that counts the number of times it was entered. So the first lock can enter since it isn’t owned, it sets the owner to your thread and the count to 1. The second lock is allowed to enter since the thread ID matches, the count increments to 2. At the end of the second lock, the count decrements to 1 again. At the end of the first, the count decrements to 0 and that resets the owner.