WhilseySoon WhilseySoon - 3 months ago 18
C# Question

Creating Threads inside recursive function

I have an app with some recursive function that in general looks like this:

threads = 0;
Algorithm(array) {
//some code...

newArray1 = array.Take(array.Length / 2).ToArray();
newArray2 = array.Skip(array.Length / 2).ToArray();

ThreadStart start1 = delegate
{
Algorithm(newArray1);
};

Thread thread1 = new Thread(start1);

ThreadStart start2 = delegate
{
Algorithm(newArray2);
};

Thread thread2 = new Thread(start2);
thread1.Start();
threads++;
thread2.Start();
threads++;
}


It doesn't matter how deep this recursion goes, the variable threads always equals 2. Why?

Answer

Yes, the threads variable is shared. Have a look at this link for use of threads with recursive functions - How to use threads with a recursive template function

Comments