Suppose I have the following C# class
class MyClass
{
private int _i;
private object _locker = new object();
public void DoSomething()
{
var b = 2;
// some work that depends on b being 2
lock(_locker)
{
_i = 3;
}
// some more work
b = -1;
// some more work
}
}
And I use it this way,
//Usage:
var myobject = new MyClass();
new Thread(new ThreadStart(() => myobject.DoSomething())).Start();
new Thread(new ThreadStart(() => myobject.DoSomething())).Start();
Can the following sequence happen?
Thread 1 is halfway through its work.
Thread 2 just starts. Sets b = 2.
Thread 1 sets b = -1.
Thread 2 is confused because it expected b to be 2 but its -1.
The important point is that b is a local variable. Will the two threads get access to the same instance of b? I understand that for the instance variable _i, this will happen. Hence the lock construct for that. But am not sure whether I need to do locking for local variables as well.
The local variable will be put on the stack when a caller enters the method
DoSomething(). Each thread operates on a separate stack and will get its own unique local variable.This part from Wikipedia for thread local storage applies to C# threading as well: