线程特定数据
作用
定义:存储和查询特定线程相关数据的一种机制
-
线程共享进程的存储空间,而我们希望每个线程访问自己的数据
-
通过线程特定数据的机制,线程特定数据操作函数可以提高线程间的数据独立性
流程
创建与线程特定数据关联的键
pthread_key_create(pthread_key_t keyp,void(destructor)(void ));
通过pthread_key_delete(pthread_key_t)删除键与线程特定数据关联
有些线程可能看到一个键值,而其他线程可能看到是另一个不同的键,这取决于系统如何调度
,解决这种竞争的办法是使用pthread_once
pthread_once_t initflag = PTHREAD_ONCE_INIT;
pthread_once(&initflag,void (initfn)(void));
initflag必须非局部变量,必须初始化为PTHREAD_ONCE_INIT;
thread_init(void)
{
phtread_key_create(&key,destructor);
}
thread_func(void arg){
pthread_once(&initflag,thread_init)
pthread_setspecific(key,const void value)//设置私有数据
pthread_getspecial(key);//获取
}
测试程序
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
static pthread_key_t key;
static pthread_once_t initflag;
thread_init(void){
pthread_key_create(&key,NULL);//清理函数未设置
}
void func(void arg)
{
pthread_once(&initflag,thread_init);
char *buf = (char*)malloc(100);
char *p ;
memset(buf,0,100);
sprintf(buf,"%s%d","hello",(int)arg);
pthread_setspecific(key,buf);
p=(void*)pthread_getspecific(key);
printf("func:phtread_self %ld %s\n",pthread_self(),p);
//删除key与线程特定空间的联系
return NULL;
}
int main()
{
pthread_t tid,tid1;
pthread_create(&tid,NULL,func,(void*)1);
pthread_create(&tid1,NULL,func,(void*)2);
pthread_join(tid,NULL);
pthread_join(tid1,NULL);
return 0;
}
输出结果
func:phtread_self 139704569833216 hello2
func:phtread_self 139704578225920 hello1