nested lock? [Archive] - C Board

PDA

View Full Version : nested lock?


George2
03-22-2008, 03:08 AM
Hello everyone,


From the sample,

http://www.albahari.com/threading/part2.html

Do you know what means "A thread can block only on the first, or outermost lock."?

I quote the related context below as well.

--------------------
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. This allows for the most natural semantics when one method calls another as follows:


static object x = new object();

static void Main() {
lock (x) {
Console.WriteLine ("I have the lock");
Nest();
Console.WriteLine ("I still have the lock");
}
Here the lock is released.
}

static void Nest() {
lock (x) {
...
}
Released the lock? Not quite!
}


A thread can block only on the first, or outermost lock.
--------------------


thanks in advance,
George

Wraithan
03-22-2008, 08:00 AM
It means that you have to unlock as many times as you lock in order for the resource to be unlocked. That way if you lock something, lock it again, then unlock it once (because that portion of the code is done with the variable but the calling portion of the code feels the need to lock it) it is still locked and you must unlock it again.

George2
03-23-2008, 08:33 AM
Thanks Wraithan,


Question answered.

It means that you have to unlock as many times as you lock in order for the resource to be unlocked. That way if you lock something, lock it again, then unlock it once (because that portion of the code is done with the variable but the calling portion of the code feels the need to lock it) it is still locked and you must unlock it again.


regards,
George