Why can't I buy an exclusive castle?

The following program prints:

Entered 3 Entered 4 Wait for Exited messages Exited 3 Exited 4 

This means that it cannot receive an exclusive resource lock. Why?

 public class Worker { public void DoIt(object resource) { Monitor.Enter(resource); Console.WriteLine("Entered " + Thread.CurrentThread.ManagedThreadId); Thread.Sleep(3000); Monitor.Exit(resource); Console.WriteLine("Exited " + Thread.CurrentThread.ManagedThreadId); } } class Program { struct Resource { public int A; public int B; } static void Main(string[] args) { Resource resource; resource.A = 0; resource.B = 1; var a = new Worker(); var b = new Worker(); var t1 = new Thread(() => a.DoIt(resource)); var t2 = new Thread(() => b.DoIt(resource)); t1.Start(); t2.Start(); Console.WriteLine("Wait for Exited messages"); Console.ReadLine(); } } 
+4
source share
1 answer

Your Resource is a structure. It is put in a box when passed to DoIt , so every DoIt call blocks another object. Change Resource as a class.

+10
source

All Articles