C# · 12月 24, 2021

c# – 同时调用相同对象的多个线程.它会引起问题吗?

假设我有以下C#类 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 }}

我用这种方式,

//Usage:var myobject = new MyClass();new Thread(new ThreadStart(() => myobject.DoSomething())).Start();new Thread(new ThreadStart(() => myobject.DoSomething())).Start();

以下序列可以发生吗?

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.

重要的一点是b是局部变量.两个线程是否可以访问b的同一个实例?我理解,对于实例变量_i,会发生这种情况.因此,锁定构造.但我不确定是否需要锁定局部变量.

解决方法 当调用者输入DoSomething()方法时,局部变量将被置于堆栈中.每个线程在一个单独的堆栈上运行,并将获得自己唯一的局部变量.

Wikipedia for thread local storage的这一部分也适用于C#线程:

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.