Reentrancy: Difference between revisions
pc>Yuron No edit summary |
Yuron [PHRhYmxlIGNsYXNzPSJ0d3BvcHVwIj48dHI+PHRkIGNsYXNzPSJ0d3BvcHVwLWVudHJ5dGl0bGUiPkdyb3Vwczo8L3RkPjx0ZD51c2VyPGJyIC8+YnVyZWF1Y3JhdDxiciAvPmludGVyZmFjZS1hZG1pbjxiciAvPnN5c29wPGJyIC8+PC90ZD48L3RyPjwvdGFibGU+] (talk | contribs) m (1 revision imported) |
(No difference)
|
Revision as of 12:46, 26 July 2019
Depends on | Atomicity |
---|
A fragment of code is “reentrant” if it can be executed correctly more than once, simultaneously.
Typically this means that the code uses only local variables and has no side-effects on any state visible externally. (A change in external state could be something like changing a file pointer having read in a character, so be careful!)
You have probably experienced re-entrant code already, in the form of recursive code. During recursive execution several copies of the relevant functions may be active, even though there is ever only one thread executing.
Puzzle: in the example
fact.c
(download it here), is the recursively called ‘factorial()’ function re-entrant code?AnswerAnswer I’d say: “yes”, as the ‘global’ variable is local to this single thread/process.
but
not if the function was used in (for example) a shared library where the values could interfere.
Re-entrancy is often important in operating system routines as (e.g.) the same system call can be made by multiple processes in an indeterminate order. On the other hand, sometimes sections of the code are not re-entrant and therefore need some form of access control.
Always think about cases when variables have to be private.