- 论坛徽章:
- 0
|
在UNIX环境高级编程12.6节里边:
例子程序将malloc分配的变量设置为线程私有数据。我想,既然malloc 有自己的锁,是线程安全的,何必还用 pthread_setspecific()把它设置成线程私有的呢?每个线程调用这个函数肯定会得到属于该线程自己的一份内存,对吗?
例子程序如下:
Figure 12.13. A thread-safe, compatible version of getenv
- #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);
- }
复制代码
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 编辑 ] |
|