线程在C#中,值类型和引用类型澄清?类型、线程

2023-09-03 16:07:47 作者:落笔画秋枫

阅读乔恩斯基特文章后,和的从MSDN这个的文章中,我仍然有一个问题的

After reading Jon Skeet article , and this article from msdn , I still have a question

让我们说我有这个code:

Let's say I have this code :

  MyPerson mp = new MyPerson(); //Field

  int g=0; //Field

  public void DoWork ()
   {
      int i;
      MyPerson mp2 = new MyPerson();  
      ...
   }

现在让我们说我有2个线程。它运行的DoWork 。 (让我们忽略,现在,比赛条件)

Now let's say I have 2 threads. which runs DoWork. ( let's ignore for now , race conditions)

他们都将看到相同的先按g 或每个线程都有自己的项目? ? (值)

Will they both see the same g or each thread will have its own item ? ? ( value )

他们都将看到相同的 MP 或每个线程都有自己的项目? (实例)

Will they both see the same mp or each thread will have its own item ?? ( instance )

他们都将看到相同的或每个线程都有自己的项目? (值)

Will they both see the same i or each thread will have its own item ? ( value )

他们都将看到相同的 MP2 或每个线程都有自己的项目? (实例)

Will they both see the same mp2 or each thread will have its own item ? ( instance )

如果他们都看到同样的,为什么我需要静态

if they both see the same , why would I need static ?

我搜索了很多关于这个话题,和无法找到的任何文章,其中指出:不同的线程,楼盘类型和值类型.. 。)的

I've searched a lot about this topic , and couldn't find any article which states : Different Threads ,ref types and value types... )

推荐答案

两个线程都只是跑的DoWork ;他们一个特定的对象上运行的DoWork 的 的。如果创建了两个线程针对不同的情况,那么 MP 先按g 将是完全不同的领域。如果创建了两个线程瞄准的同一个实例,则 MP 先按g 将共享的但的也不能保证,除非你使用同步的线程将看到由其他线程所做的更改或挥发性访问。

Neither thread simply "runs DoWork"; they run DoWork on a particular object. If the two threads are created targeting different instances, then mp and g will be completely separate fields. If the two threads are created targeting the same instance, then mp and g will be shared but it is not guaranteed that the threads will see changes made by the other thread unless you use synchronization or volatile access.

例如:

var obj = new SomeObject();
Thread thread1 = new Thread(obj.DoWork);
Thread thread2 = new Thread(obj.DoWork); // clearly targeting the same instance

VS

var obj = new SomeObject();
Thread thread1 = new Thread(obj.DoWork);
obj = new SomeObject();
Thread thread2 = new Thread(obj.DoWork); // targeting a different instance

局部变量 MP2 严格具体到每一个线程。

The local variables i and mp2 are strictly specific to each thread.

附加说明:即使是单独的字段/本地人,如果有些code。在 ... 之后重新分配 MP MP2 引用的相同的对象的,那么他们将被争吵过相同的对象;相同的同步/ 将适用于挥发规则。

Additional note: even if they are separate fields/locals, if some of the code in the ... later reassigns mp or mp2 to refer to the same object, then they will be squabbling over the same object; the same synchronization / volatile rules will apply.