Inconsistency between Monitor And Lock

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
"c#: The complete referece" book writes "microsoft says that lock is precisely equivalent to Monitor.Enter()/Exit()", but in the following case, they seem to differ in their behaviour.


Please verify whether the following observation is correct or not:

________________

public void fun()

{


Monitor.Enter(x);

Console.WriteLine("Locked X");

Thread.Sleep(100);

x=y;

Monitor.Exit(x);

Console.WriteLine("Released X");


Monitor.Enter(y);

Console.WriteLine("Locked Y");

Thread.Sleep(500);

Monitor.Exit(y);

Console.WriteLine("Released X");


}


__________________

In the above function let x,y be some objects.

I started 2 threads on the same funtion fun().

Now both of these threads will try to lock "x" (the delay is deliberately inserted to achieve


this). Now only one of them will suceed. But the thread that succeeded will change the x to point to y, and then release the lock on the new "x" (which is now y). The first thread that was waiting will never acquier the lock on the original "x", becoz the it will never be signalled by any thread.

The o/p coincides with my observation.


<output of the program>


Locked X

Released X

Locked Y

Released Y

<and the program hangs>

_________________


Now replace the Monitr.Enter(x)/Exit(x) statements with lock(x) statement and


Monitor.Enter(y)/Exit(y) with lock(y). In this case, when the first thread releases the lock on "x", both the threads enter CS, becoz both x & y now point to same object. ie even though the object is same, both the threads are able to acquire locks on it thru different references at the same time.


<output of the program>


Locked X

Locked X

Released X

Locked Y

Released X

Locked Y

Released Y

Released Y


as we can observe when the first thred released "X", the second thread succeeded in lock(x). the first thread then succeeded in lock(y), eventhough both x and y point to the same object.


__________


is it the case that, monitor locks the object refered to by "x" whereas "lock" locks the variable "x"?


Can somebody pls give me more details?


--------------------------------

From: vasudeva enjamuri

www.cse.iitb.ac.in/vasudeva




View the full article
 
Back
Top