Locking an object that may change during code execution

Suppose I have a thread that blocks an object reference

Theme number 1

lock(myObj) { ... } 

later in the code I have myObj = new XYZObj();

and then Thread # 2 blocks it

 lock(myObj) { ... } 

Will this code be thread safe if the object reference has changed? When the object reference changes, is the first lock still valid?

+5
source share
3 answers

Locks work on instances, not variables.
The lock statement will contain its own instance reference so that it only exits the instance you entered.

spec says:

where x is an expression of the reference type, exactly equivalent to

 System.Threading.Monitor.Enter(x); try { ... } finally { System.Threading.Monitor.Exit(x); } 

, except that x is evaluated only once.

If you reassign a variable between two locks, you will get two valid locks in two different instances.

In general, however, you should never do this; this is a recipe for subtle mistakes and race conditions.
You should only lock locked objects for reading.

+5
source

Not. They will both be blocked on different objects.

According to MSDN

The best practice is to define a private object to lock or a private static object variable to protect data common to all instances.

+3
source

Will this code be a safe thread

The lock(myObj) { ... } is safe only until a new reference to the object is bound to the variable myObj . Addition:. In addition, it is safe if any data shared between streams that are used non-atomically mutate inside an object lock, only use non-atomic mutations inside locks on the same object.

That way, every time you enter a lock for myObj , the actual reference object is what is used to lock, not your variable. If you change the variable to a link to a new object, you are actually blocking different objects in different locks, which is clearly not what you wanted. But, again, the next time you return to the first lock, the first and second lock objects can be synchronized again, and it will be safe again. May be!

As you can see, this behavior is completely broken. Is this a hypothetical question or are you really doing that?

+2
source

All Articles