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.
There is nothing wrong in calling same function from different threads. If you want to ensure that your variables are consistent it is advisable to provide thread synchronization mechanisms to prevent crashes, racearound conditions.
both threads will be writing to same memory area, so yes, it'll be overwritten.
Because all threads share the same heap, and the heap is where all instance variables are stored, multiple threads can attempt to use the same object's instance variables concurrently.
Multithreading in Java is a process of executing two or more threads simultaneously to maximum utilization of CPU. Multithreaded applications execute two or more threads run concurrently. Hence, it is also known as Concurrency in Java.
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:
In other words, data in a static or global variable is normally always located at the same memory location, when referred to by threads from the same process. Variables on the stack however are local to threads, because each thread has its own stack, residing in a different memory location.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With