下面说一下线程存储的具体用法。
pthread_key_t无论是哪一个线程创建,其他所有的线程都是可见的,即一个进程中只需phread_key_create()一次。看似是全局变量,然而全局的只是key值,对于不同的线程对应的value值是不同的(通过pthread_setspcific()和pthread_getspecific()设置)。
int pthread_key_create(pthread_key_t *key, void (*destr_function) (void *))
不论哪个线程调用pthread_key_create(),所创建的key都是所有线程可访问的,但各个线程可根据自己的需要往key中填入不同的值,这就相当于提供了一个同名而不同值的全局变量。在LinuxThreads的实现中,TSD池用一个结构数组表示:
static struct pthread_key_struct pthread_keys[PTHREAD_KEYS_MAX] = { { 0, NULL } }; |
创建一个TSD就相当于将结构数组中的某一项设置为"in_use",并将其索引返回给*key,然后设置destructor函数为destr_function。
int pthread_setspecific(pthread_key_t key, const void *pointer) void * pthread_getspecific(pthread_key_t key)写入(pthread_setspecific())时,将pointer的值(不是所指的内容)与key相关联,而相应的读出函数则将与key相关联的数据读出来。数据类型都设为void *,因此可以指向任何类型的数据。
#include <stdio.h> #include <pthread.h> pthread_key_t key; void echomsg(int t) { printf("destructor excuted in thread %d,param=%d\n",pthread_self(),t); } void * child1(void *arg) { pthread_t tid=pthread_self(); printf("thread %d enter\n",tid); pthread_setspecific(key,(void *)tid); sleep(2); printf("thread %d returns %d and key %d\n",tid,pthread_getspecific(key),key); sleep(5); } void * child2(void *arg) { pthread_t tid=pthread_self(); printf("thread %d enter\n",tid); pthread_setspecific(key,(void *)tid); sleep(1); printf("thread %d returns %d and key %d\n",tid,pthread_getspecific(key),key); sleep(5); } int main(void) { pthread_t tid1,tid2; printf("this is main thread\n"); pthread_key_create(&key,(void (*)(void *))echomsg); pthread_create(&tid1,NULL,child1,NULL); pthread_create(&tid2,NULL,child2,NULL); sleep(10); pthread_key_delete(key); printf("main thread exit\n"); return 0; }
线程私有存储空间--pthread_key_t,布布扣,bubuko.com
原文:http://blog.csdn.net/yusiguyuan/article/details/21785641