Multiple threads invoking the same objects work simultaneously. Could this cause problems?

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 that 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 two threads access the same instance of b? I understand that for the _i instance variable this will happen. Therefore, the lock construct is built for this. But I'm not sure if I need to block local variables.

+6
source share
1 answer

The local variable will be pushed onto the stack when the calling user enters the DoSomething() method. Each thread runs on a separate stack and will receive its own unique local variable.

This part from Wikipedia for local thread storage also applies to a C # stream:

In other words, data in a static or global variable is usually always located in the same memory location when threads from the same process are mentioned. However, the variables in the stack are local to the threads, because each thread has its own stack, a location in a different memory, etc.

+11
source

Source: https://habr.com/ru/post/896552/


All Articles