加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 04:21:16 所属栏目:百科 来源:网络整理
导读:假设我有以下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 }}
假设我有以下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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读