Can two threads execute in the same lock region concurrently?

  • Thread starter Thread starter Russell Stuart
  • Start date Start date
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();
}
}
 
Russell Stuart said:
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.

Please see my reply in the C# newsgroup - there's no need to multipost.
 
Jon Skeet said:
Please see my reply in the C# newsgroup - there's no need to multipost.

Sorry, of course it wasn't in the C# newsgroup. It was in this
newsgroup. So why the repeat post?
 
Sorry, of course it wasn't in the C# newsgroup. It was in this
newsgroup. So why the repeat post?

Becuase I originally posted the query last night on 247. When
I came in this morning I couldn't see it - so I posted it
using a normal nntp client.

Then both posts appeared. Sorry for the confusion.
 
Russell Stuart said:
Becuase I originally posted the query last night on 247. When
I came in this morning I couldn't see it - so I posted it
using a normal nntp client.

Then both posts appeared. Sorry for the confusion.

Fair enough :)
 
Back
Top