在linux中,同一进程下所有线程是共享全局变量的,但有时候会有这样的需求,某一个线程想单独用于某个全局变量。这就有了TSD,Thread Specific Data。
使用TSD时需要创建一个全局的键值,每个线程都通过键值来设置和获取自己所独有的全局变量。
使用TSD分为以下几个步骤
1、创建一个键值,key为一个键值,destructor是一个destructor函数,
如果这个参数不为空,那么当每个线程结束时,系统将调用这个函数来释放绑定在这个键上的内存块
int pthread_key_create(pthread_key_t *key, void (*destructor)(void*));
2、通过键值设置线程私有数据,key为键值,pointer是私有数据的地址,该函数将私有数据的地址告诉键值key
int pthread_setspecific(pthread_key_t key,const void *pointer));
3、通过键值获取私有数据
void *pthread_getspecific(pthread_key_t key);
4、销毁键值,键值使用完毕将键值销毁释放
pthread_key_delete(pthread_key_t key);
简单的测试代码
#include <pthread.h>
#include <stdio.h>
pthread_key_t key;
pthread_t thid1;
pthread_t thid2;
void* thread2(void* arg)
{
printf("thread:%lu is running\n", pthread_self());
int key_va = 20 ;
pthread_setspecific(key, (void*)key_va);
printf("thread:%lu return %d\n", pthread_self(), (int)pthread_getspecific(key));
}
void* thread1(void* arg)
{
printf("thread:%lu is running\n", pthread_self());
int key_va = 10;
pthread_setspecific(key, (void*)key_va);
printf("thread:%lu return %d\n", pthread_self(), (int)pthread_getspecific(key));
}
int main()
{
pthread_key_create(&key, NULL);
pthread_create(&thid1, NULL, thread1, NULL);
pthread_create(&thid2, NULL, thread2, NULL);
pthread_join(thid1, NULL);
pthread_join(thid2, NULL);
pthread_key_delete(key);
return 0;
}
执行结果