Path: utzoo!utgpu!water!watmath!clyde!att!osu-cis!tut.cis.ohio-state.edu!rutgers!ucsd!ucbvax!pasteur!postgres!anton From: anton@postgres.uucp (Jeff Anton) Newsgroups: comp.unix.wizards Subject: Re: reentrant vs. non-reentrant code Message-ID: <4790@pasteur.Berkeley.EDU> Date: 31 Jul 88 20:26:47 GMT References: <1670001@hpcilzb.HP.COM> <3409@phri.UUCP> Sender: news@pasteur.Berkeley.EDU Reply-To: anton@postgres.UUCP (Jeff Anton) Organization: Postgres Research Group, UC Berkeley Lines: 93 In article <3409@phri.UUCP> roy@phri.UUCP (Roy Smith) writes: >In article <1670001@hpcilzb.HP.COM> tedj@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@postgres.berkeley.edu