您的位置:首页 > 其它

线程私有数据

2014-07-27 21:16 477 查看
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>

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

return NULL;
}

void * thread1(void *arg)
{
int tsd = 0;
pthread_t thid2;
printf("thread1 %lu is running \n",pthread_self());
pthread_setspecific(key,(void *)tsd);/*将tsd值为 0设置到key中*/
// printf("thread1 %lu returns %d\n",pthread_self(),pthread_getspecific(key));
pthread_create(&thid2,NULL,thread2,NULL);
sleep(2);
printf("thread1 %lu 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: