线程的私有数据(TSD-Thread-Specific Data)

      在线程内部,线程私有数据可以被各个函数访问到,但它对其他线程是屏蔽的。

      使用线程数据时,首先要为每个线程数据创建一个相关联的键。在各个线程内部,都使用这个公用的键来指代线程数据,但是在不同的线程中,这个键代表的数据是不同的。也就是说,key一旦被创建,所有线程都可以访问它,但各线程可根据自己的需要往key中填入不同的值。这相当于提供了一个同名而不同值的全局变量,一键多值。

      操作线程私有数据的函数主要有4个:

  • pthread_key_create(创建一个键)
  • pthread_setspecific(为一个键设置线程私有数据)
  • pthread_getspecific(从一个键读取线程私有数据)
  • pthread_key_delete(删除一个键)

      以下代码示例如何创建、使用和删除线程的私有数据:

#include <stdio.h>
#include <string.h>
#include <pthread.h>

//声明键
pthread_key_t key;

//线程1中设置本线程的私有数据为5,并且之后获取这个数据并打印到屏幕
void * thread1(void *arg)
{
    int tsd=5;
    printf("Thread %u is running\n",pthread_self());
    pthread_setspecific(key,(void*)tsd);
    printf("Thread %u returns %d\n",pthread_self(),pthread_getspecific(key));
}

//线程2中设置本线程的私有数据为4,并且之后获取这个数据并打印到屏幕
void * thread2(void *arg)
{
    int tsd=4;
    printf("Thread %u is running\n",pthread_self());
    pthread_setspecific(key,(void*)tsd);
    printf("Thread %u returns %d\n",pthread_self(),pthread_getspecific(key));
}

int main(void)
{
    pthread_t thid1,thid2;
    printf("Main thread begins running\n");

	//创建这个键
    pthread_key_create(&key,NULL);

	//创建2个子线程
    pthread_create(&thid1,NULL,thread1,NULL);
    pthread_create(&thid2,NULL,thread2,NULL);

	//等待2个子线程返回
    int status1,status2;
    pthread_join(thid1,(void *)&status1);
    pthread_join(thid2,(void *)&status2);

	//删除键
    pthread_key_delete(key);

    printf("main thread exit\n");
    return 0;
}

运行结果:



      上述2个线程分别将tsd作为线程私有数据。从程序运行来看,两个线程对tsd的修改互不干扰。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值