Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why cannot I acquire exclusive lock?

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();
        }
    }
like image 864
Prankster Avatar asked Apr 13 '09 20:04

Prankster


1 Answers

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.

like image 122
Anton Tykhyy Avatar answered Oct 12 '22 01:10

Anton Tykhyy