Reservation and Recursion

Would it be a true statement to say that every recursive function must be reentrant?

+3
source share
5 answers

If you mean by reentrant that a further function call can begin before the previous one is finished, then yes, all recursive functions turn out to be reentrant, because recursion involves re-entry in this sense.

However, "reuse" is sometimes used as a synonym for "thread safety", which introduces many other requirements, and in this sense the answer is no. In single-threaded recursion, we have a special case when only one "instance" of the function will be executed, because the "idle" instances on the stack are waiting for the return of their "child" instance.

+2
source

'Reentrant' usually means that a function can be entered several times at once by two different threads.

To be reentrant, it must do things like protect / block access to a static state.

( ) / , .

: .

+1

.

, , ? ?

:

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);
}

, , , , , - . .

0

, , () . () , .

global i;

    factorial()
    { if i == 0 return 1;
      else { i = i -1; return i*factorial();

    }

.

0

. .

A recursive function should be able to process the record during its operation, but access is carried out in a controlled manner, and not by other threads.

0
source

Source: https://habr.com/ru/post/1750265/


All Articles