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