Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lock on an object that might change during code execution

Let's suppose I have a thread that locks on an object reference

Thread #1

lock(myObj) { ... }

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

and then Thread #2 locks on it

lock(myObj) { ... }

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

like image 394
gsb Avatar asked Dec 20 '11 16:12

gsb


2 Answers

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

The spec says:

where x is an expression of a reference-type, is precisely equivalent to

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

except that x is only evaluated once.

If you re-assign the variable between the two locks, you will get two valid locks on two different instances.

In general, however, you should never do that; it's a recipe for subtle bugs and race conditions.
You should only lock on dedicated readonly lock objects.

like image 64
SLaks Avatar answered Nov 14 '22 23:11

SLaks


No. They will both be locking on different objects.

According to MSDN

Best practice is to define a private object to lock on, or a private static object variable to protect data common to all instances.

like image 37
Mongus Pong Avatar answered Nov 14 '22 21:11

Mongus Pong