我有一个带有递归功能的应用程序,通常看起来像这样:
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++;
}
这种递归的深度并不重要,变量线程总是等于2.为什么?
答案 0 :(得分:2)
我假设您没有等待线程完成。您需要在Algorithm
方法中添加对Thread.Join()
方法(documentation)的调用,该方法“阻止调用线程,直到此实例表示的线程终止”(您将执行此操作)适用于thread1
和thread2
)。此外,您需要使用Interlocked
类“为多个线程共享的变量提供原子操作”来增加线程数(请参阅Increment method)。
话虽如此,您应该记住,为单个任务创建新线程的效率非常低(创建线程/上下文切换会产生性能开销)。相反,您应该使用CLR提供的线程池。如果您想了解有关如何使用任务并行来有效利用线程池的更多信息,请参阅this link
答案 1 :(得分:1)
是的,共享threads
变量。查看此链接以使用具有递归函数的线程 - How to use threads with a recursive template function