Sunday, March 13, 2011

Reenterant code

If a code can be interrupted in the middle and can then safely be called again before its previous invocations have been completed, and once the reentered invocation completes, the previous invocations should be able to resume execution correctly then the code is called to be reentrant.

A subroutine that is directly or indirectly recursive should be reentrant.
The definition of reentrancy differs from that of thread-safety in multi-threaded environments. Reentrant code is used in single threaded environment.

It should follow:
  • It should not invoke any non-reentrant subroutines,
  • It has no access to mutable (non-constant) static or global variables or data structures,
  • The code is not self-modifying.
A non reentrant code:
int g_var = 1;

int f()
{
g_var = g_var + 2;
return g_var;
}

int g()
{
return f() + 2;
}

The following code is reentrant:

int f(int i)
{
return i + 2;
}

int g(int i)
{
return f(i) + 2;
}

No comments:

Post a Comment