Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

444 Thread Control Chapter 12


#include <stdio.h>
int getchar_unlocked(void);
int getc_unlocked(FILE *fp);
Both return: the next character if OK,EOFon end of file or error
int putchar_unlocked(intc);
int putc_unlocked(intc,FILE *fp);
Both return:cif OK,EOFon error
These four functions should not be called unless they aresurrounded by calls to
flockfile(orftrylockfile)andfunlockfile.Otherwise, unpredictable results
can occur (i.e., the types of problems that result from unsynchronized access to data by
multiple threads of control).
Once you lock theFILEobject, you can make multiple calls to these functions
beforereleasing the lock. This amortizes the locking overhead across the amount of
data read or written.

Example


Figure12.11shows a possible implementation ofgetenv(Section 7.9). This version is
not reentrant. If two threads call it at the same time, they will see inconsistent results,
because the string returned is stored in a single static buffer that is shared by all threads
callinggetenv.
#include <limits.h>
#include <string.h>
#define MAXSTRINGSZ 4096
static char envbuf[MAXSTRINGSZ];
extern char **environ;
char *
getenv(const char *name)
{
int i, len;
len = strlen(name);
for (i = 0; environ[i] != NULL; i++) {
if ((strncmp(name, environ[i], len) == 0) &&
(environ[i][len] == ’=’)) {
strncpy(envbuf, &environ[i][len+1], MAXSTRINGSZ-1);
return(envbuf);
}
}
return(NULL);
}
Figure 12.11 Anonreentrant version ofgetenv
Free download pdf