Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what happens with lock when thread gets closed while the lock is set

I was wondering, If in a thread i have a lock statement and if that specific thread is closed while the lock is set, what happens with the lock ?

Are the other threads going to have access to the critical zone(does my specific lock variable get unlocked) or does the lock remain active and bricks my app ? If so, What solutions do i have to avoid the brick?

like image 720
Alex Avatar asked Dec 03 '22 10:12

Alex


1 Answers

A lock statement:

lock (x)
{
    ...
}

is interpreted by the compiler in the resulting IL to:

Monitor.Enter(x);
try 
{
   ...
}
finally 
{
   Monitor.Exit(x);
}

So as you can see if an exception is thrown, the lock is released because of the finally statement. So even if you terminate the thread with Thread.Abort (which causes a ThreadAbortException to be thrown inside the thread) which you should ABSOLUTELY NEVER do, the lock will be released.

like image 132
Darin Dimitrov Avatar answered Dec 05 '22 23:12

Darin Dimitrov