pthread_setspecific的一段代码

//IBM developer上copy的。简单明了
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

pthread_key_t   key;
void echomsg(int t)
{
        printf("destructor excuted in thread %d,param=%d\n",pthread_self(),t);
}
void * child1(void *arg)
{
        int tid=pthread_self();
        printf("thread %d enter\n",tid);
        pthread_setspecific(key,(void *)tid);
        sleep(2);
        printf("thread %d returns %d\n",tid,pthread_getspecific(key));
        sleep(5);
}
void * child2(void *arg)
{
        int tid=pthread_self();
        printf("thread %d enter\n",tid);
        pthread_setspecific(key,(void *)tid);
        sleep(1);
        printf("thread %d returns %d\n",tid,pthread_getspecific(key));
        sleep(5);
}
int main(void)
{
        int tid1,tid2;
        printf("hello\n");
        pthread_key_create(&key,(void (*)(void*))echomsg);
        pthread_create((pthread_t *)&tid1,NULL,child1,NULL);
        pthread_create((pthread_t *)&tid2,NULL,child2,NULL);
        sleep(10);
        pthread_key_delete(key);
        printf("main thread exit\n");
        return 0;
}




改进版。传指针

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

pthread_key_t   key;

struct info
{
        int i;
        char buf[512];
};
void echomsg(info* t)
{
        printf("destructor excuted in thread %d,param=%d\n",pthread_self(),t->i);
        delete t;//前面传入的是内存的地址。所以可以delete
}
void * child1(void *arg)
{
        int tid=pthread_self();
        printf("thread %d enter\n",tid);
        struct info *in=new info();
        in->i=tid;
        pthread_setspecific(key,(void *)in);//这里传入的是in的内容,也就是new出来的内存的地址
        sleep(2);
        struct info *in2=(struct info*)pthread_getspecific(key);
        printf("thread %d returns %d\n",tid,in2->i);
        sleep(5);
}
/*
void * child2(void *arg)
{
        int tid=pthread_self();
        printf("thread %d enter\n",tid);
        pthread_setspecific(key,(void *)tid);
        sleep(1);
        printf("thread %d returns %d\n",tid,pthread_getspecific(key));
        sleep(5);
}
*/
int main(void)
{
        int tid1,tid2;
        printf("hello\n");
        pthread_key_create(&key,(void (*)(void*))echomsg);
        pthread_create((pthread_t *)&tid1,NULL,child1,NULL);
//      pthread_create((pthread_t *)&tid2,NULL,child2,NULL);
        sleep(10);
        pthread_key_delete(key);
        printf("main thread exit\n");
        return 0;
}


总结:
在32位机器上,(void*)传入的就是32位一块内存区域。
比如你
1.传入void*(int)就是把int值放入这块内存,取出来的时候千万*不要*用"*"号
2.传入(void*)(&int)就是把int指针放入内存,你get出来的时候就*要*记得用“*”号了

总之,记住你传入的是什么东西。很重要。int,short之类直接传值简单点。而char*,class,struct应该传指针。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值