locks within locks

D

DaTurk

I have a question concerning nested locks. I just noticed that I have
an object declared in my parent class that I use as the lock. But what
I noticed is that in one of the childs methods, I lock that object,
then while still in the critical section I call one of my inherited
methods, and lock the same object.

So it's esentially this

object _lock = new object();

lock(_lock)
{
lock(_lock)
{

//Do Something

}
}

Is this OK to do? It seems to be working I think.
 
M

Marc Gravell

Yes; locking structures are /generally/ re-entrant, meaning if you already
hold the lock you can effectively take out another... to avoid scenarios
with deadlocking yourself.

Marc
 
B

Brian Gideon

DaTurk,

Yep, that's fine because it is locking on the same object.

What you do need to look out for is the order of locks when different
objects are used. A common deadlock scenario exists when you have two
different critical sections that lock on two different objects in
different orders. There are plenty of others, but this is common
enough to mention. For example, the following code would eventually
deadlock.

void CritialSection1()
{
lock (a)
{
lock (b)
{
// whatever
}
}
}

void CritialSection2()
{
lock (b)
{
lock (a)
{
// whatever
}
}
}

Brian
 
S

Samuel R. Neff

While that works fine, I would be concerned with the fact that you
noticed the double-lock after the fact. If you're not fully aware of
what is being locked when and what is already locked when certain code
is running, then it's more likely you'll create deadlock situations or
innefficient code (i.e., not a deadlock but code that's unnecessarily
waiting on other code).

In general it's a good practice to keep locked sections as small as
possible and be very aware of what is running inside locked sections.

Sam
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top