Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is lock() type-cast safe?

Tags:

c#

locking

public class A { }
public class B:A { }

void foo()
{
   A a = new B();
   B b = a as B;
}

for a given instance setup, will lock(a) be equivalent to lock(b) ?

I mean, will locking be mutually exclusive? If I lock(a) in one thread and lock(b) in another thread, will I get a mutually exclusive access to that single instance of B created earlier?

like image 611
Andy Avatar asked Dec 17 '22 00:12

Andy


1 Answers

Yes lock(a){} is equivalent to lock(b){}.

The lock() documentation states that the lock statement marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object of reference type.

a and b are both the same object so yes they are equivalent. Actually a and b are both references to the same object.

A cast operation between reference types does not change the run-time type of the underlying object; it only changes the type of the value that is being used as a reference to that object. Source.

A quick test program shows that it does indeed behave the way it is documented:

namespace ConsoleApplication2
{
    public class A { }
    public class B : A { }

    class Program
    {
        static A a = new B();

        static void MyThread()
        {
            B b = a as B;
            lock (b)
            {
                Console.WriteLine("b lock acquired");
                Console.WriteLine("releasing b lock");
            }

        }


        static void Main(string[] args)
        {
            System.Threading.Thread t = new System.Threading.Thread(MyThread);

            lock(a)
            {
                Console.WriteLine("a lock acquired");               
                t.Start();
                System.Threading.Thread.Sleep(10000);
                Console.WriteLine("Releasing a lock");
            }
        }
    }
}

a lock acquired
... 10 seconds pass
releasing a lock
b lock acquired
releasing b lock

like image 85
Brian R. Bondy Avatar answered Dec 28 '22 08:12

Brian R. Bondy