reentrant vs. non-reentrant code

Barry Shein bzs at prep.ai.mit.edu
Sun Aug 7 01:59:23 AEST 1988


The simplest way to understand re-entrant code is to just understand
that functionally it requires that all variables accessed (plus or
minus intended global side-effects, a special case) are private to the
invocation of the subroutine, like automatic variables (a C routine
with no statics or globals is re-entrant because all automatics are
stack relative, perhaps somewhere there is an implementation which
violates that but it would be a questionable implementation.)

If you think of it in psuedo-assembler consider:

	ADD	A,B,C		# add A to B yielding C
A:	.WORD
B:	.WORD
C:	.WORD

NOT re-entrant since a subsequent entry to this code would modify
the same A,B,C locations.

	ADD	0(FP),4(FP),8(FP)

If FP is a pointer to an area provided on entry to the code and every
entry will have its own FP value (typically a stack area, but not
necessarily) then no matter how many times you are simultaneously
executing that area of code the source and destinations will be
to/from different areas of memory, voila', re-entrant.

There's nothing more to it.

The usefulness is obvious, sometimes while running a piece of code you
can get an interrupt (eg. running an output routine and a timer goes
off, say you were doing a printf() when the clock DINGed) and then,
before the interrupt is finished, it calls the same code (eg.  the
timer handler uses printf().) If printf() were re-entrant then it
would work out, returning from the interrupt later would continue with
your original printf().) Note: printf() is inherently non-re-entrant
(why? because it will always modify the stdout buffer, thus you could
get output interleaved or worse if FILE * items weren't updated
correctly when the interrupt occurred.) That example is purposely bad
to cause you to think thru the issues.

	-Barry Shein, Whereabouts Unknown



More information about the Comp.unix.wizards mailing list