开发者

Is lock() type-cast safe?

开发者 https://www.devze.com 2022-12-30 03:47 出处:网络
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) ?
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 lockin开发者_开发技巧g 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?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号