我想为 strerror_r 调用创建线程本地缓冲区并编写我自己的线程安全 char * my_strerror(int) ,它将使用线程本地缓冲区并调用 strerror_r。
在阅读 R.Stevens 在 Unix 环境中的高级编程中关于 pthread_getspecific() 的示例时,我感到有差异 -为什么在下面的示例中使用互斥锁?
书中的例子:
#include <limits.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
静态 pthread_key_t 键;
静态 pthread_once_t init_done = PTHREAD_ONCE_INIT;
pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER;
extern char **环境;
静态空白
线程初始化(无效)
{
pthread_key_create(&key, 免费);
}
字符 *
getenv(常量字符*名称)
{
诠释 i, len;
字符 *envbuf;
pthread_once(&init_done, thread_init);
pthread_mutex_lock(&env_mutex);
envbuf = (char *)pthread_getspecific(key);
如果(envbuf == NULL){
envbuf = malloc(ARG_MAX);
如果(envbuf == NULL){
pthread_mutex_unlock(&env_mutex);
返回(空);
}
pthread_setspecific(键,envbuf);
}
len = strlen(名称);
for (i = 0; environ[i] != NULL; i++) {
if ((strncmp(name, environ[i], len) == 0) &&
(环境[i][len] == '=')) {
strcpy(envbuf, &environ[i][len+1]);
pthread_mutex_unlock(&env_mutex);
返回(环境缓冲区);
}
}
pthread_mutex_unlock(&env_mutex);
返回(空);
}