可重入和递归
说每个递归函数都需要可重入是正确的说法吗?
Would it be a true statement to say that every recursive function needs to be reentrant?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
说每个递归函数都需要可重入是正确的说法吗?
Would it be a true statement to say that every recursive function needs to be reentrant?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(4)
如果可重入意味着对函数的进一步调用可能会在前一个函数结束之前开始,那么是的,所有递归函数都恰好是可重入的,因为从这个意义上来说,递归意味着可重入。
然而,“可重入”有时被用作“线程安全”的同义词,这引入了很多其他要求,从这个意义上来说,答案是否定的。在单线程递归中,我们有一种特殊情况,即一次只会执行一个函数“实例”,因为堆栈上的“空闲”实例都在等待其“子”实例返回。
If by reentrant you mean that a further call to the function may begin before a previous one has ended, then yes, all recursive functions happen to be reentrant, because recursion implies reentrance in that sense.
However, "reentrant" is sometimes used as a synonym for "thread safe", which is introduces a lot of other requirements, and in that sense, the answer is no. In single-threaded recursion, we have the special case that only one "instance" of the function will be executing at a time, because the "idle" instances on the stack are each waiting for their "child" instance to return.
不,我记得有一个与静态(全局)变量一起使用的阶乘函数。拥有静态(全局)变量不利于可重入,并且该函数仍然是递归的。
这个函数是递归的并且是不可重入的。
No, I recall a factorial function that works with static (global) variables. Having static (global) variables goes against being reentrant, and still the function is recursive.
This function is recursive and it's non-reentrant.
“可重入”通常意味着两个不同的线程可以同时多次进入该函数。
为了可重入,它必须执行诸如保护/锁定对静态状态的访问之类的操作。
另一方面,递归函数不需要保护/锁定对静态的访问,因为它一次只执行一个语句。
所以:不。
'Reentrant' normally means that the function can be entered more than once, simultaneously, by two different threads.
To be reentrant, it has to do things like protect/lock access to static state.
A recursive function (on the other hand) doesn't need to protect/lock access to static state, because it's only executing one statement at a time.
So: no.
一点也不。
例如,为什么递归函数不能拥有静态数据?它不应该能够锁定关键部分吗?
考虑一下:
这并不是说编写递归和可重入函数很容易,也不是说它是常见模式,也不是说以任何方式推荐它。但这是可能的。
Not at all.
Why shouldn't a recursive function be able to have static data, for example? Should it not be able to lock on critical sections?
Consider:
This does not go to say that writing a recursive and reentrant function is easy, neither that it is a common pattern, nor that it is recommended in any way. But it is possible.