Path: utzoo!utgpu!attcan!uunet!yale!cmcl2!phri!roy From: roy@phri.UUCP (Roy Smith) Newsgroups: comp.unix.wizards Subject: Re: reentrant vs. non-reentrant code Message-ID: <3409@phri.UUCP> Date: 31 Jul 88 16:12:17 GMT References: <1670001@hpcilzb.HP.COM> Reply-To: roy@phri.UUCP (Roy Smith) Organization: Public Health Research Inst. (NY, NY) Lines: 62 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: fact (i) int i; { return (i<2 ? i : i*fact(i-1)); } If you call fact(5), the first instance of i is 5. Fact calls itself with an argument of i=4. Now you have two instances of fact in the process of being executed. This works because i is automatic; each invocation of fact gets a new piece of memory in which to store i. Now, change the routine to look like: fact (i) int i; { static j; j = i; return (j<2 ? j : j*fact(j-1)); } and you end up with a bit of non-reentrant code: each invocation of fact still has its own instance of i, but they all share the same j. The second time fact gets called, it overwrites the value of j still being used. Actually, what I've just shown is a bit of code which is not recursively reentrant, which is not quite the same thing as not being reentrant. A better example would be something like: sayfoo() { static char *str = "foo\n"; while (*str) { putchar (*str); str++; } } The first time you call sayfoo(), it prints "foo\n", but each other time you call it, it just returns without printing anything. Any code with static variables in it is likely to be non-reentrant. This generally means Fortran code is non-reentrant since Fortran uses static storage. Self modifying code is also almost certainly non-reentrant. Sometimes code is reentrant except for certain windows of vulnerability which much be locked around. A typical example is a Unix device driver. -- Roy Smith, System Administrator Public Health Research Institute {allegra,philabs,cmcl2,rutgers}!phri!roy -or- phri!roy@uunet.uu.net "The connector is the network"