:''For other uses of the term, see
Reentrant (disambiguation)''
A
computer program or
routine is described as 'reentrant' if it can be safely called
recursively and
concurrently from multiple processes. To be reentrant, a function must hold no static data, must not return a pointer to static data, must work only on the data provided to it by the caller, and must not call non-reentrant functions.
Despite a common misconception, this is not the same as being designed in such a way that a single copy of the program's instructions, in memory, can be shared.
The
kernel code or the code implementing synchronization like
semaphore is generally not reentrant because it handles the shared memory (i.e., the 'environment', of which there is normally only one instance). Note that multiple levels of 'user/object/process
priority' and/or
multiprocessing greatly complicate the control of reentrant code.
Examples
In the following piece of
C code, neither functions
f nor
g are reentrant.
int g_var = 1;
int f()
{
g_var = g_var + 2;
return g_var;
}
int g()
{
return f() + 2;
}
int main()
{
g();
return 0;
}
In the above,
f depends on a
global variable ''g_var''; thus, if two threads execute it and access g_var concurrently, then the result varies depending on the timing of the execution. Hence, f is not reentrant. Neither is
g; it calls
f, which is not reentrant.
These slightly-altered versions 'are' reentrant:
int f(int i)
{
int priv = i;
priv = priv + 2;
return priv;
}
int g(int i)
{
int priv = i;
return f(priv) + 2;
}
int main()
{
g(1);
return 0;
}
See also
★
Thread-safe
External links
★ Article "
Use reentrant functions for safer signal handling" by
Dipak K Jha
★
Writing Reentrant and Thread-Safe Code