R
Russell Stuart
I always believed .Net monitors were a superset of the Java
synchronization mechanisms. The code below produces both
"Thread 1" and "Thread 2" lines, implying that two threads
are both executing in locked region guarded by the same
monitor. I thought that wasn't supposed to happen. Am I
wrong? It was compiled and run under VS 2003.
If you run it under the debugger then the behaviour changes -
only "Thread 1" lines are produced. This is what I expected
to happen in all cases.
using System;
using System.Threading;
public class Test {
Thread t1, t2;
public void Run1() {
Thread.Sleep(1000);
lock (this) {
Monitor.Pulse(this);
t2.Interrupt();
for (;
Console.WriteLine("Thread 1");
}
}
public void Run2() {
lock (this) {
try {
Monitor.Wait(this);
}
catch (ThreadInterruptedException) {
Console.WriteLine("2 Interrupted");
}
for (;
Console.WriteLine("Thread 2");
}
}
public void Go() {
t1 = new Thread(new ThreadStart(Run1));
t2 = new Thread(new ThreadStart(Run2));
t1.Start();
t2.Start();
}
public static void Main() {
new Test().Go();
}
}
synchronization mechanisms. The code below produces both
"Thread 1" and "Thread 2" lines, implying that two threads
are both executing in locked region guarded by the same
monitor. I thought that wasn't supposed to happen. Am I
wrong? It was compiled and run under VS 2003.
If you run it under the debugger then the behaviour changes -
only "Thread 1" lines are produced. This is what I expected
to happen in all cases.
using System;
using System.Threading;
public class Test {
Thread t1, t2;
public void Run1() {
Thread.Sleep(1000);
lock (this) {
Monitor.Pulse(this);
t2.Interrupt();
for (;
Console.WriteLine("Thread 1");
}
}
public void Run2() {
lock (this) {
try {
Monitor.Wait(this);
}
catch (ThreadInterruptedException) {
Console.WriteLine("2 Interrupted");
}
for (;
Console.WriteLine("Thread 2");
}
}
public void Go() {
t1 = new Thread(new ThreadStart(Run1));
t2 = new Thread(new ThreadStart(Run2));
t1.Start();
t2.Start();
}
public static void Main() {
new Test().Go();
}
}