Is the lock safe ()?

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

for this instance installation would lock(a) equivalent to lock(b) ?

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

+4
source share
1 answer

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

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

a and b are the same objects, so yes, they are equivalent. In fact, a and b are references to the same object.

The cast operation between reference types does not change the runtime type of the base object; it only changes the type of value that is used as a reference to this object. Source

The quick check program shows that it really behaves as 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"); } } } } 

locked lock ... after 10 seconds
castle liberation
b lock | release lock b

+12
source

Source: https://habr.com/ru/post/1309841/


All Articles