问题描述
在阅读 Jon Skeet 文章 和 这篇来自 msdn 的文章,我还有一个问题
After reading Jon Skeet article , and this article from msdn , I still have a question
假设我有这个代码:
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 )
他们会看到相同的 i
还是每个线程都有自己的项目?(价值)
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 )
如果他们都看到相同的内容,我为什么需要 static
?
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
将是完全独立的字段.如果两个线程是针对 same 实例创建的,则 mp
和 g
将共享 但 它不是保证线程将看到另一个线程所做的更改,除非您使用同步或 volatile
访问.
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
对
var obj = new SomeObject();
Thread thread1 = new Thread(obj.DoWork);
obj = new SomeObject();
Thread thread2 = new Thread(obj.DoWork); // targeting a different instance
局部变量 i
和 mp2
严格针对每个线程.
The local variables i
and mp2
are strictly specific to each thread.
附加说明:即使它们是单独的字段/本地,如果 ...
中的某些代码稍后重新分配 mp
或 mp2
引用同一个对象,那么他们就会为同一个对象争吵;将应用相同的同步/volatile
规则.
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.
这篇关于C# 中的线程、值类型和引用类型说明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!