strerror_r 呼び出し用のスレッド ローカル バッファーを作成し、スレッド ローカル バッファーを使用して strerror_r を呼び出す独自のスレッド セーフな char * my_strerror(int) を作成したいと考えています。
R.Stevens による Unix 環境の高度なプログラミングの pthread_getspecific() に関する例を読んでいるときに矛盾を感じます -以下の例でミューテックスが使用されているのはなぜですか?
本からの例:
#include <limits.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
static pthread_key_t キー;
static pthread_once_t init_done = PTHREAD_ONCE_INIT;
pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER;
extern char **environ;
静的ボイド
thread_init(void)
{
pthread_key_create(&key, free);
}
文字 *
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);
リターン (ヌル);
}
pthread_setspecific(キー、envbuf);
}
len = strlen(名前);
for (i = 0; 環境[i] != NULL; i++) {
if ((strncmp(name, 環境[i], len) == 0) &&
(environ[i][len] == '=')) {
strcpy(envbuf, &environ[i][len+1]);
pthread_mutex_unlock(&env_mutex);
戻ります (envbuf);
}
}
pthread_mutex_unlock(&env_mutex);
リターン (ヌル);
}