Recursion and locking

  • Thread starter Thread starter Curious
  • Start date Start date
C

Curious

Hi,
I have a datastructure that sorts elements by a key. Now in some
circumstances a key may occur twice and so I would like to change the
old key value by adding 1.

To do this I am doing it recursively within a lock statement. My
problem is that since the myQueue is already locked, if the method is
called again recursively, should it block on the lock statement till
the lock is released?

public void Postpone(key)
{
lock(myQueue)
{
object = myQueue.Remove(key);
try
{

myQueue.Add(object, key+1);
}
catch(Exception)
{
Postpone(key+1);
}
}
}


Can somone help me out
Thanks in Advance
 
why not move the lock to outside of the Postpone method, i.e. the calling
method locks around the call to Postpone not inside the Postpone method

HTH

Ollie Riches
 
Curious said:
I have a datastructure that sorts elements by a key. Now in some
circumstances a key may occur twice and so I would like to change the
old key value by adding 1.

To do this I am doing it recursively within a lock statement. My
problem is that since the myQueue is already locked, if the method is
called again recursively, should it block on the lock statement till
the lock is released?

No - Monitor.Enter (which is what happens under the hood) effectively
just increments the lock count if you lock it within the same thread.
In other words, the lock is recursive.

See http://www.pobox.com/~skeet/csharp/threads/locking.shtml (half way
down) for more on this.

Jon
 
Curious,

No, it will not. Since the calls are occuring on the same thread, you
will not be blocked.

However, it is a bit inefficient, and it would be better if you did
something like this:

public void Postpone(int key)
{
// Lock on the queue.
lock (myQueue)
{
InternalPostpone(key);
}
}

private void InternalPostpone(int key)
{
object = myQueue.Remove(key);
try
{
myQueue.Add(object, key+1);
}
catch(Exception)
{
InternalPostpone(key+1);
}
}

This way, you don't have excessive locks being allocated on the same
thread.

Hope this helps.
 
Back
Top