What is a Re-entrant procedure?

rrazd picture rrazd · Aug 11, 2011 · Viewed 7.8k times · Source

What is a re entrant procedure and can you give an example scenario of when it is used?

Edit: Also, can multiple processes access a re entrant procedure in parallel?

Please provide a different way of explaining than wikipedia as I don't totally understand their description hence my question here

Answer

T.E.D. picture T.E.D. · Aug 11, 2011

The idea behind re-entrancy is that the routine may be called while it is in the middle of executing already and it will still work right.

Generally this is achieved by it using only parameters and local variables declared on the stack (in C terms, no static locals). It would also be important that it not lock any global resources during execution.

Now, you may ask, "How would such a weird thing as a routine being run multiple times at once happen?" Well, some ways this could happen are:

  • The routine is recursive (or mutually-recursive with some other set of routines).
  • It gets called by another thread.
  • It gets called by an interrupt.

If any of these happen, and the routine is modifying a global (or C static local), then the new execution could potentially wipe out the changes the first execution made. As an example, if that global was used as a loop control variable, it might cause the first execution, when it finally gets to resume, to loop the wrong number of times.