Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of using a non-static local variable in a lock?

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?

like image 579
imak Avatar asked Feb 24 '11 15:02

imak


People also ask

Why static variables are not thread safe?

Static variables are not thread safe. Instance variables do not require thread synchronization unless shared among threads. But, static variables are always shared by all the threads in the process. Hence, access to static variable is not thread safe.

What is instance variable in c sharp?

Instance variables are non-static variables and are declared in a class but outside any method, constructor or block. As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed.

Can static variables be changed c#?

Static methods cannot access or change the values of instance variables or the this reference (since there is no calling object for them), and static methods cannot call non-static methods. However, non-static methods have access to all variables (instance or static) and methods (static or non-static) in the class.


1 Answers

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.

like image 63
jason Avatar answered Oct 04 '22 12:10

jason