Reputation: 6699
A couple of times I have came across this code where a local variable in a class ( its NOT a static variable) has been used in a lock.
public class SomeClass
{
private object obj = new object();
....
....
lock(obj)
{
}
}
Is there any point of locking given that its an instance variables?
Upvotes: 6
Views: 1172
Reputation: 59523
A static lock would be useful for controlling access to a static variable. An instance lock would be useful for controlling access to an instance variable.
There is no point at all in using a local lock object to protect a local variable (unless it is a captured outer variable of an anonymous function or in an iterator), since other threads will not have access to either the lock or the variable.
Upvotes: 5
Reputation: 241751
Is there any point of locking given that its an instance variables?
Multiple threads could be acting on the same instance and a lock is needed for thread-safety. Think, for example, of a shared queue.
Upvotes: 14