可重入和递归

Ton*_*ion 5 recursion reentrancy

说每个递归函数都需要是可重入的,这是一个真实的陈述吗?

Yuv*_*dam 0

一点也不。

例如,为什么递归函数不能拥有静态数据?它不应该能够锁定关键部分吗?

考虑:

sem_t mutex;
int calls = 0;

int fib(int n)
{
    down(mutex); // lock for critical section - not reentrant per def.
    calls++; // global varible - not reentrant per def.
    up(mutex);

    if (n==1 || n==0)
        return 1;
    else
        return fib(n-1) + fib(n-2);
}
Run Code Online (Sandbox Code Playgroud)

这并不是说编写递归和可重入函数很容易,也不是说它是一种常见模式,也不是说以任何方式推荐它。但这是可能的。