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?
I assume that you were not waiting for the threads to finish. You would need to add inside your Algorithm
method a call to Thread.Join()
method ( documentation ), which "blocks the calling thread until the thread represented by this instance terminates" (you would do this for both thread1
and thread2
). Also, you would need to use Interlocked
class which "provides atomic operations for variables that are shared by multiple threads" to increment number of threads (see Increment method ).
Having said that, you should keep in mind that creating new Threads for individual tasks is highly inefficient (there is performance overhead with creating threads/context switching). Instead, you should use Thread Pool provided by the CLR. If you want more information on how to use Task Parallelism to efficiently utilize Thread Pool, see this link
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.