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

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

概述假设我有以下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 假设我有以下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.

总结

以上是内存溢出为你收集整理的c# – 同时调用相同对象的多个线程.它会引起问题吗?全部内容,希望文章能够帮你解决c# – 同时调用相同对象的多个线程.它会引起问题吗?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1262934.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-08
下一篇 2022-06-08

发表评论

登录后才能评论

评论列表(0条)

保存