-->

Threading in C# , value types and reference types

2020-08-26 04:47发布

问题:

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

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();  
      ...
   }

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

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

  • 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 )

  • 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... )

回答1:

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.

For example:

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

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

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.



回答2:

The variables g and mp are 'global' to the containing class, so these will be the same objects seen by both threads. i is a local variable that is declared in the DoWork event; subsequently this will only be 'visible' to the background/alternative thread.

They don't 'see' the same, so the static keyword in this case has no relevence.

I hope this helps.