Posted on 2009-07-05 14:27
Prayer 阅读(198)
评论(0) 编辑 收藏 引用 所属分类:
LINUX/UNIX/AIX
#include <stdio.h>
#include <pthread.h>
pthread_key_t key;
void echomsg(char *s)
{
printf("thread auto free private varible %s\n",s);
free(s);
s = NULL;
}
void * child1(void *arg)
{
//int tid = pthread_self();
char * str = (char*)malloc(20);
memset(str,0,20);
sprintf(str,"%s","thread child1");
printf("thread %s enter\n",str);
pthread_setspecific(key,(void*)str);
sleep(2);
//printf("thread %d returns %d\n",tid,pthread_getspecific(key));
sleep(5);
}
void * child2(void * arg)
{
//int tid = pthread_self();
char * str = (char*)malloc(20);
memset(str,0,20);
sprintf(str,"%s","thread child2");
printf("thread %s enter \n",str);
pthread_setspecific(key,(void*)str);
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((pthread_key_t*)&key,(void*)echomsg);
pthread_create((pthread_t*)&tid1,NULL,child1,NULL);
pthread_create((pthread_t*)&tid2,NULL,child2,NULL);
sleep(10);
pthread_key_delete(key);
return 0;
}