I have to pass multiple parameters to a thread. I have wrapped them into a class object. In which one variable (double array) i want pass it as reference (I am expecting the result in this variable). How does it possible?
class param
{
int offset = 0;
double[] v = null;
}
param p = new param();
p.v = new double[100]; // I want to pass this(v) variable by reference
p.offset = 50;
....
thread1.Start(p);
Passing by by reference refers to a method of passing the address of an argument in the calling function to a corresponding parameter in the called function. In C, the corresponding parameter in the called function must be declared as a pointer type.
Pass-by-reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the argument by using its reference passed in. The following example shows how arguments are passed by reference.
Passing Multiple Arguments to Threads. When passing multiple arguments to a child thread, the standard approach is to group the arguments within a struct declaration, as shown in Code Listing 6.9. The address of the struct instance gets passed as the arg to pthread_create() .
There are many solutions. One is, you can use ParameterizedThreadStart
for that.
param p = new param();
// start the thread, and pass in your variable
Thread th = new Thread(new ParameterizedThreadStart(MyThreadMethod));
th.Start(p);
public void MyThreadMethod(object o)
{
// o is your param
param pv = (param)o;
}
You could also just pass the param
variable when you declare the thread:
static void Main()
{
param p = new param();
p.v = new double[100]; // I want to pass this(v) variable as reference
p.offset = 50;
Thread t = new Thread ( () => MyThreadMethod(p) );
t.Start();
}
static void MyThreadMethod(param p)
{
//do something with p
Console.WriteLine(p.v.Length);
Console.WriteLine(p.offset);
}
Check out Joseph Albahari's free e-book on threading here.
I like this approach since you don't need to deal with other objects -- just create a lambda in your Thread constructor and you're off to the races.
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With