views:

179

answers:

1

The following program prints:

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

Meaning that it cannot acquire an exclusive lock on resource. 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();
        }
    }
+7  A: 

Your Resource is a struct. It is boxed when passed to DoIt, so each call to DoIt locks a different object. Change Resource to be a class.

Anton Tykhyy