Let's say I have this code:
object o1 = new Object();
object o2 = o1;
Is obtaining a lock on o1 the same as obtaining a lock on o2? (If o1 is locked, will locking o2 block till o1 is released?)
If it locked the reference itself, locking would be profoundly useless. The problem is, references themselves are copied by value, so you'd always be locking some temporary copy that gets thrown away immediately.
So that's not how it works. The lock is obtained on the instance that the reference references, not the reference itself.
Is obtaining a lock on
o1
the same as obtaining a lock ono2
?
Yes.
It works with something called a sync-block that is part of every object instance. But functionally you can think of it as using the object as a key in a Dictionary.
Locking on the reference would be the same as locking on a Value type, with the same problems.
Yes, because a lock is taken on an object, not on a object reference. o2 = o1
copies the reference, not the object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With