Pass reference of object to a new Thread

走远了吗. 提交于 2019-11-28 06:02:48

问题


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

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.


回答1:


By reference.

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.




回答2:


10 thread ? how do you plan to maintain the data integrity of the _newObject ? Saying that copies will not be passed, only the reference will be used. If you going to call the method MyMethod(object MyObject) in 10 different threads will the MyObject be different objects ?? if not you are better off refractoring the method.

Also you should remember that a thread is just a liner set of instructions to be executed. So just because of using multiple threads your object size will not increase in the memory.
the very advantage of multi threading is to make use of different threads to process your instructions, and does not make copies of objects.




回答3:


Assuming that your MyClass is a class, then the reference of the object is only passed to the new thread, since it is a reference type(read more on reference types on MSDN), i would also suggest that you use a lock in order avoid deadlock issues you can do that simply by using the lock keyword




回答4:


To be more precise it's send by reference copy.

Since this is a reference type, only a reference is copied in this case, and not all data.

That's why you have to care about locking mechanisms in cases where more then one thread accesses the data this object refers to.



来源:https://stackoverflow.com/questions/12298801/pass-reference-of-object-to-a-new-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!