微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.

原文地址:https://www.jb51.cc/csharp/91912.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐