gpt4 book ai didi

c# - 在递归函数中创建线程

转载 作者:行者123 更新时间:2023-12-03 13:17:06 27 4
gpt4 key购买 nike

我有一个带有一些递归功能的应用程序,通常看起来像这样:

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。为什么?

最佳答案

我假设您不是在等待线程完成。您需要在Algorithm方法内添加对Thread.Join()方法(documentation)的调用,该方法“阻塞调用线程,直到该实例代表的线程终止”(您需要对thread1thread2都执行此操作)。另外,您将需要使用Interlocked类,该类“为多个线程共享的变量提供原子操作”,以增加线程数(请参阅Increment method)。

话虽如此,您应该记住,为单个任务创建新线程效率极低(创建线程/上下文切换会带来性能开销)。相反,您应该使用CLR提供的线程池。如果您想了解有关如何使用任务并行性有效利用线程池的更多信息,请参见this link

关于c# - 在递归函数中创建线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38823379/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com