A computer program or routine is described as reentrant if it can be safely called recursively or 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.
f and g are not reentrant.
int g_var = 1; int f() { g_var = g_var + 2; return g_var; } int g() { return f() + 2; }
In the above, f depends on a global variable g_var; thus, if two processes 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 g_var = 1; int f(int i) { g_priv = i; g_priv = g_priv + 2; return g_priv; } int g(int i) { g_priv = i; return f(g_priv) + 2; }
Both of the new versions are designed to leave the global variable g_var alone -- to have a parameter passed to them, work on it privately, and return the result, not to go out and munge some possibly-shared object.
Eintrittsinvarianz | Réentrance | Codice rientrante | Реентерабельность
This article is licensed under the GNU Free Documentation License.
It uses material from the
"Reentrant".
Home Page • arts • business • computers • games • health • hospitals • home • kids & teens • news • physicians • recreation• reference • regional • science • shopping • society • sports • world