Reentrancy, reentrant function
A computer program or routine is described as reentrant if it can be safely called again before its previous invocation has been completed (i.e it can be safely executed concurrently).
To be reentrant, a computer program or routine:
* Must hold no static (or global) non-constant data.
* Must not return the address to static (or global) non-constant data.
* Must work only on the data provided to it by the caller.
* Must not call non-reentrant computer programs or routines.
A really clean reentrant package will require no additional RAM beyond the stack and/or heap.
The standard library functions (malloc() and free()) are not normally reentrant, which would be problematic in a multithreaded application.If source code is available, this should be straightforward to rectify by locking resources using semaphore , mutex etc.
example of a re-entrant function:
int power(int x, int count)
{
if (count<=0) return(1);
return(x*power(x, count-1));
}
Suppose we modify the function as follows:
double power(double x)
{
if (count<=0)return(1);
–count;
return(x*power(x));
}
where exp is now defined as a global variable, accessible to many other functions. The function still works correctly. However, if this function was called and then an interrupt which calls the same function came along while it is executing, it will return an incorrect result. The variable count is fixed in memory; it is not unique to each call, and is therefore shared between callers, a disaster in an interrupting or multi-threading environment .
Thread-safe vs Re-entrant :
An operation is “thread-safe” if it can be performed from multiple threads safely, even if the calls happen simultaneously on multiple threads.
An operation is re-entrant if it can be performed while the operation is already in progress (perhaps in another context). This is a stronger concept than thread-safety, because the second attempt to perform the operation can even come from within the same thread