2012-11-14 154 views
0

我想爲strerror_r調用創建線程本地緩衝區,並編寫自己的線程安全char * my_strerror(int),它將使用線程本地緩衝區並調用strerror_r。pthread_getspecific和互斥鎖

在閱讀有關pthread_getspecific()在R.Stevens的Unix環境下的高級編程中的例子時,我感覺不一致 - 爲什麼在下面的例子中使用互斥量?從書

實施例:

 
#include <limits.h> 
#include <string.h> 
#include <pthread.h> 
#include <stdlib.h> 

static pthread_key_t key; 
static pthread_once_t init_done = PTHREAD_ONCE_INIT; 
pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER; 

extern char **environ; 

static void 
thread_init(void) 
{ 
    pthread_key_create(&key, free); 
} 

char * 
getenv(const char *name) 
{ 
    int  i, len; 
    char *envbuf; 

    pthread_once(&init_done, thread_init); 
    pthread_mutex_lock(&env_mutex); 
    envbuf = (char *)pthread_getspecific(key); 
    if (envbuf == NULL) { 
     envbuf = malloc(ARG_MAX); 
     if (envbuf == NULL) { 
      pthread_mutex_unlock(&env_mutex); 
      return(NULL); 
     } 
     pthread_setspecific(key, envbuf); 
    } 
    len = strlen(name); 
    for (i = 0; environ[i] != NULL; i++) { 
     if ((strncmp(name, environ[i], len) == 0) && 
      (environ[i][len] == '=')) { 
      strcpy(envbuf, &environ[i][len+1]); 
      pthread_mutex_unlock(&env_mutex); 
      return(envbuf); 
     } 
    } 
    pthread_mutex_unlock(&env_mutex); 
    return(NULL); 
} 

+2

爲了保護'environ'變量,例如'putenv'。鎖定調用的位置很糟糕,不過,最好緊跟在'strlen'之後。 – chill

+0

請重寫爲答案。 –

回答

2

需要互斥爲保護environ可變的,例如,從putenv。鎖定電話很糟糕,不過,最好在strlen之後。