reentrant vs. non-reentrant code

Jeff Anton anton at postgres.uucp
Mon Aug 1 06:26:47 AEST 1988


In article <3409 at phri.UUCP> roy at phri.UUCP (Roy Smith) writes:
>In article <1670001 at hpcilzb.HP.COM> tedj at hpcilzb.HP.COM (Ted Johnson) writes:
>> Can someone please explain the difference between "reentrant" and
>> "non-reentrant" code?  Thanks!
>
>	Reentrant code is, quite simply, code you can reenter without ill
>effect.  Usually this means that each invocation of the code gets its own
>set of variables, although this is not a sufficient condition to make
>something reentrant.  Take a typical example in C, a recursve factorial
>routine:
>

Reentrantcy is generally not a problem for most code since most code
deals with one thread of execution.  However, you might run against the
problem if you have a signal handler which uses code which you also use
durring normal execution.

Bewarned, recursive is not reentrant.  Code can be recursive without being
reentrant.  Since recursion is part of the design of a code sample, that
code can be written to do recursion only when the environment of the code
is ready.  You could, for example, have a static variable in a recursive
routine so long as you no longer use that variable after you make the
recursive call, or only use it after the last recursive call.

Also, you can have reentrant code without being recursive.  This is very
common and most C code is reentrant.  Recursion is part of the design of
code.  For example:

/* recursive and reentrant */
unsigned
fact1(i)
unsigned i;
{
	if (i < 3)
		return(i);
	return (i*fact1(i-1));
}

/* reentrant */
unsigned
fact2(i)
unsigned i;
{
	unsigned v;

	if (i < 3)
		return(i);
	v = 1;
	while (i > 1)
		v *= i--;
	return(v);
}

/* recursive - kids, don't try this at home */
unsigned
fact3(i)
unsigned i;
{
	static	unsigned	v;

	if (i < 3)
		return(v = i);
	fact3(i-1);
	return(v *= i);
}

/* badness */
unsigned
fact4(i)
unsigned i;
{
	static	unsigned v;

	if (i < 3)
		return(i);
	v = 1;
	while (i > 1)
		v *= i--;
	return(v);
}

main()
{
	printf("fact1(5) = %u\n", fact1(5));
	printf("fact2(5) = %u\n", fact2(5));
	printf("fact3(5) = %u\n", fact3(5));
	printf("fact4(5) = %u\n", fact4(5));
}
--------------------------------------------------------------
At the end of the journey don't except me to stay - Pink Floyd
						Obscured by Clouds

Jeff Anton	anton at postgres.berkeley.edu



More information about the Comp.unix.wizards mailing list