免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1954 | 回复: 2
打印 上一主题 下一主题

[C] 请教个unix线程私有数据的问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-05-29 23:02 |只看该作者 |倒序浏览
在UNIX环境高级编程12.6节里边:
    例子程序将malloc分配的变量设置为线程私有数据。我想,既然malloc 有自己的锁,是线程安全的,何必还用 pthread_setspecific()把它设置成线程私有的呢?每个线程调用这个函数肯定会得到属于该线程自己的一份内存,对吗?

例子程序如下:

Figure 12.13. A thread-safe, compatible version of getenv


  1. #include <limits.h>
  2. #include <string.h>
  3. #include <pthread.h>
  4. #include <stdlib.h>

  5. static pthread_key_t key;
  6. static pthread_once_t init_done = PTHREAD_ONCE_INIT;
  7. pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER;

  8. extern char **environ;

  9. static void
  10. thread_init(void)
  11. {
  12.     pthread_key_create(&key, free);
  13. }

  14. char *
  15. getenv(const char *name)
  16. {
  17.     int     i, len;
  18.     char    *envbuf;

  19.     pthread_once(&init_done, thread_init);
  20.     pthread_mutex_lock(&env_mutex);
  21.     envbuf = (char *)pthread_getspecific(key);
  22.     if (envbuf == NULL) {
  23.         envbuf = malloc(ARG_MAX);
  24.         if (envbuf == NULL) {
  25.             pthread_mutex_unlock(&env_mutex);
  26.             return(NULL);
  27.         }
  28.         pthread_setspecific(key, envbuf);
  29.     }
  30.     len = strlen(name);
  31.     for (i = 0; environ[i] != NULL; i++) {
  32.         if ((strncmp(name, environ[i], len) == 0) &&
  33.           (environ[i][len] == '=')) {
  34.             strcpy(envbuf, &environ[i][len+1]);
  35.             pthread_mutex_unlock(&env_mutex);
  36.             return(envbuf);
  37.         }
  38.     }
  39.     pthread_mutex_unlock(&env_mutex);
  40.     return(NULL);
  41. }

复制代码


          Thread-specific data, also known as thread-private data, is a mechanism for storing and finding data associated with a particular thread. The reason we call the data thread-specific, or thread-private, is that we'd like each thread    to access its own separate copy of the data, without worrying about synchronizing access with other threads.

[ 本帖最后由 wliang511 于 2008-5-29 23:14 编辑 ]

论坛徽章:
0
2 [报告]
发表于 2008-05-29 23:59 |只看该作者
为什么书上都不说线程调度的问题,好像记得linux内核线程和用户线程有个什么对应关系,然后用
pthread_set_concurrency()可以提高效率。。到现在这方面的概念仍然是模糊的。有大人知道这方面的资料吗?
   不过也许这个问题本身就有问题...

论坛徽章:
0
3 [报告]
发表于 2008-05-30 09:11 |只看该作者
我想,既然malloc 有自己的锁,是线程安全的,何必还用 pthread_setspecific()把它设置成线程私有的呢?

-------malloc是线程安全的?即使它是线程安全的,也不代表它分配出来的内存是线程私有的,只是说调用这个函数不会在多线程环境下变得不可预测
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP