本文共 2613 字,大约阅读时间需要 8 分钟。
Reentrancy
POSIX.1 provides a way to manage FILE objects in a thread-safe way. You can use flockfile and ftrylockfile to obtain a lock associated with a given FILE object. This lock is recursive: you can acquire it again, while you already hold it, without deadlocking. Although the exact implementation of the lock is unspecified, all standard I/O routines that manipulate FILE objects are required to behave as if they call flockfile and funlockfile internally.
#includeint ftrylockfile(FILE *fp);void flockfile(FILE *fp);
If the standard I/O routines acquire their own locks, then we can run into serious performance degradation when doing character-at-a-time I/O. In this situation, we end up acquiring and releasing a lock for every character read or written. To avoid this overhead, unlocked versions of the character-based standard I/O routines are available.
#includeint getchar_unlocked(void);int getc_unlocked(FILE *fp);int putchar_unlocked(int c);int putc_unlocked(int c, FILE *fp);
#include#include #define MAXSTRINGSZ 4096static 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;}
A nonreentrant version of getenv
#include#include #include #include extern char **environ;pthread_mutex_t env_mutex;static pthread_once_t init_done=PTHREAD_ONCE_INIT;static void thread_init(void){ pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&env_mutex,&attr); pthread_mutexattr_destroy(&attr);}int getenv_r(const char *name, char *buf, int buflen){ int i, len, olen; pthread_once(&init_done, thread_init); len=strlen(name); pthread_mutex_lock(&env_mutex); for(i=0;environ[i]!=NULL;i++) { if((strncmp(name,environ[i],len)==0)&& (environ[i][len]=='=')) { olen=strlen(&environ[i][len+1]); if(olen>=buflen) { pthread_mutex_unlock(&env_mutex); return ENOSPC; } strcpy(buf, &environ[i][len+1]); pthread_mutex_unlock(&env_mutex); return 0; } } pthread_mutex_unlock(&env_mutex); return ENOENT;}
A reentrant (thread-safe) version of getenv
转载地址:https://blog.csdn.net/myfather103/article/details/79975134 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!