简体   繁体   English

在C#中使用递归时,代码是线性处理还是伪并行处理?

[英]When using recursion in C#, is the code processed linearly or in pseudo parallel?

I'm currently writing a program in C#, a language I'm not too familiar with, and I've been noticing some unexpected values when using recursion. 我目前正在用不太熟悉的语言C#编写程序,并且在使用递归时一直注意到一些意外值。 My question is, when using recursion in C#, are the function calls thrown on the stack and processed like in Java, or does C# try and implement fork()/pthread pseudo parallelism to increase op time? 我的问题是,在C#中使用递归时,函数调用是否像Java中一样抛出到堆栈上并进行处理,还是C#尝试实现fork()/ pthread伪并行性以增加操作时间?

or does C# try and implement fork()/pthread pseudo parallelism to increase op time? 还是C#尝试实现fork()/ pthread伪并行性以增加操作时间?

No. Each recursive call will be processed linearly. 否。每个递归调用将被线性处理。 If you are calling your method from Parallel.For/Parallel.Foreach or in some other multi threaded way, then you can expect non linear execution. 如果要从Parallel.For/Parallel.Foreach或以其他一些多线程方式调用方法,则可以期望非线性执行。

Talking about C# and fork in the same sentence is kind of weird. 在同一句子中谈论C#fork有点奇怪。 Although alternatives exists to run .NET on Linux, it was created for Windows, since fork() is a POSIX system call (aka not Windows') your question lack of sense. 尽管存在在Linux上运行.NET的替代方法,但它是为Windows创建的,因为fork()是POSIX系统调用(又名Windows),因此您的问题缺乏意义。

Besides that, there is nothing cleaver behind recursion in C#. 除此之外,在C#中,递归没有任何意义。 Just normal methods calls pushed onto the stack. 只是普通方法调用被压入堆栈。 It doesn't even count with tail recursion . 甚至不包括tail recursion

C# does recursion just like any other C-like language: parameters get put on the stack and the method is called in order. C#像其他任何类似C的语言一样进行递归:将参数放在堆栈上,并按顺序调用该方法。

It is done the same way in C, C++, Java, ... besides recursion tends to be hard to parallelize because the result of call n tends to depend upon the results of call n+1 . 它在C,C ++,Java等中以相同的方式完成,除了递归往往难以并行化,因为调用n的结果往往取决于调用n + 1的结果。

When you use recursion in C#, it is done in one thread. 在C#中使用递归时,它是在一个线程中完成的。 Just look at your call stack in debug mode to prove it to yourself 只需在调试模式下查看您的调用堆栈即可向自己证明

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM