pthread_key_setspecific和pthread_key_getspecific 用法

pthread_setspecific(key,(void *)tsd);

相当于key=tsd。让别的函数也可以用到tsd的值。如果我们在线程中用到全局变量,但是只是这个全局变量key,但是每个线程都有他的独立空间,虽然key名字一样,但是存储的空间是不一样,做到每个线程对这个全局变量互不影响。这个全局空间的大小是(void *)类型,也就是4个字节空间。



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

pthread_key_t key;
void test_xiayu(void)
{
	
    printf(" test thread %p returns %d\n",pthread_self(),pthread_getspecific(key));
}

void * thread2(void *arg)
{
    int tsd = 5;
    printf("thread2 %p is running\n",pthread_self());
    pthread_setspecific(key,(void *)tsd);/* 将tsd值为5设置到key中*/
    tsd=7;
    //printf("thread2 %p returns %d\n",pthread_self(),pthread_getspecific(key));

    test_xiayu();
    return NULL;
}
void * thread1(void *arg)
{
    int tsd = 0;
    pthread_t thid2;
    printf("thread1 %p is running \n",pthread_self());
    pthread_setspecific(key,(void *)tsd);/*将tsd值为 0设置到key中*/
    pthread_create(&thid2,NULL,thread2,NULL);
    sleep(2);
    test_xiayu();
    //printf("thread1 %p returns %d\n",pthread_self(),pthread_getspecific(key));
    return NULL;
}
void test1()
{
    pthread_t thid1;
    printf("main thread begins running\n");
    pthread_key_create(&key,NULL);

    pthread_create(&thid1,NULL,thread1,NULL);
    sleep(3);
    pthread_key_delete(key);
    printf("main thread exit\n");
}
int main(int argc, char **argv)
{
#if 1
    test1();
#endif
    return 0;
}
/**
 *  * 主线程创建了线程thread1,线程thread1创建了thread2.两个线程分别将tsd作
 *   * 为线程私有数据。从程序运行结果可以看出,两个线程tsd的修改互不干扰,可
 *    * 以看出thread2先于thread1结束,线程在创建thread2后,睡眠5秒等待thread2
 *     * 执行完毕。可以看出thread2对tsd的修改并没影响到thread1的tsd的取值.
 *      */


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值