【问题标题】:pthread_getspecific and mutex lockpthread_getspecific 和互斥锁
【发布时间】:2012-11-02 23:22:53
【问题描述】:

我想为 strerror_r 调用创建线程本地缓冲区并编写我自己的线程安全 char * my_strerror(int),它将使用线程本地缓冲区并调用 strerror_r。

在阅读 R.Stevens 在 Unix 环境中的高级编程中关于 pthread_getspecific() 的示例时,我觉得有差异 - 为什么在下面的示例中使用互斥锁?

书中的例子:

#include #include #include #include 静态 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); 返回(空); }

【问题讨论】:

  • 为了保护environ 变量免受putenv 之类的影响。锁定调用位置不好,不过最好紧跟在strlen 之后。

标签: pthreads mutex thread-local


【解决方案1】:

需要互斥锁来保护environ 变量,例如putenv。锁定调用位置不好,不过最好紧跟在strlen 之后。

【讨论】:

    猜你喜欢
    • 2018-05-23
    • 2010-12-17
    • 2015-10-26
    • 1970-01-01
    • 2010-09-16
    • 2021-02-03
    • 2013-10-10
    • 2014-02-15
    • 2013-06-06
    相关资源
    最近更新 更多