线程特定数据

线程特定数据

作用

定义:存储和查询特定线程相关数据的一种机制

  1. 线程共享进程的存储空间,而我们希望每个线程访问自己的数据

  2. 通过线程特定数据的机制,线程特定数据操作函数可以提高线程间的数据独立性

流程

创建与线程特定数据关联的键

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值