将对象的引用传递给新线程 [英] Pass reference of object to a new Thread

查看:133
本文介绍了将对象的引用传递给新线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含非常大的double的3D数组的对象,我需要启动一个需要该数组数据的新线程,因此我要么需要启动一个传递该对象的新线程(其中包含一个大量其他数据也发送给新线程,或者我只是将3D数组传递给新线程. 对于第一个解决方案,我只需执行以下操作:

I have an object that contains a very large 3D-array of doubles and I need to start a new thread that need the data of this array, so I will either need to start a new thread passing the object (which contains a whole lot of other data too) to the new thread or I just pass the 3D-array to the new thread. For the first solution I would simply do the following:

MyClass
{
    ...
    public double[,,] _data = new double[x,y,z];
    ...
}

MyMethod(object MyObject)
{
    //do stuff with (MyObject as MyClass)
}

MyClass _newObject = new MyClass();

Thread thread = new Thread(new ParameterizedThreadStart(MyMethod));
thread.Start(_newObject);

现在的问题是:当我将对象_newObject传递给新线程时,该对象是通过引用发送到该线程的,还是该对象被复制且新线程使用的副本?问题在于该对象包含大约300MB的数据,并且使用副本几乎是不可能的,因为我需要启动大约10个需要使用该对象数据的线程.

My question now: As I pass the object _newObject to the new thread, is that object sent to the thread by reference or is the object copied and the copy used by the new thread? The problem is that the object contains data of around 300MB and it would be almost impossible if copies are used since I need to start around 10 threads that need to use data of that object.

推荐答案

通过引用.

如果更改线程中的数据,它将更改您放入的原始数据.如果您在线程外更改数据,则线程将看到已修改的数据,这同样适用.

If you change the data in your thread it will change the original data you put in. Same applies if you change the data outside the thread your thread will see the modified data.

您需要适当的锁定机制,以便在从多个线程访问数据时不会冲突.

You need proper locking mechanisms so that it will not collide when accessing the data from multiple threads.

这篇关于将对象的引用传递给新线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆