假設我有下面的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
,會發生這種情況。因此,lock
構造。但我不確定是否需要爲局部變量進行鎖定。
'b'是本地的,因此對每個線程都是唯一的。 –
如果'_i'剛剛分配了兩次相同的值,爲什麼不考慮在啓動線程之前在非併發的代碼段中移動賦值? (或者當他們完成時) –