#include #include pthread_key_t key; void destroyFunc(void * data) { fprintf(stderr,"destroying [%s]\n",(const char *)data); } void * task(void * data) { int i; if(pthread_setspecific(key,((int)data)%2 ? "data is odd" : "data is even")) { fprintf(stderr,"Pb set specific\n"); return((void *)0); } for(i=0;i<100*1000*1000;i++); fprintf(stderr,"stored in thread %d : %s\n", (int)pthread_self(), /* ugly cast ! */ (const char *)pthread_getspecific(key)); return((void *)0); } int main(void) { pthread_t th1,th2; void * result; if(pthread_key_create(&key,destroyFunc)) { fprintf(stderr,"Pb key create\n"); return(1); } if(pthread_setspecific(key,"first thing stored")) { fprintf(stderr,"Pb set specific\n"); return(1); } if(pthread_create(&th1,(pthread_attr_t *)0,task,(void *)1)) { fprintf(stderr,"Pb create\n"); return(1); } if(pthread_create(&th2,(pthread_attr_t *)0,task,(void *)2)) { fprintf(stderr,"Pb create\n"); return(1); } if(pthread_join(th1,&result)) { fprintf(stderr,"Pb join\n"); return(1); } if(pthread_join(th2,&result)) { fprintf(stderr,"Pb join\n"); return(1); } fprintf(stderr,"stored in main thread : %s\n", (const char *)pthread_getspecific(key)); if(pthread_key_delete(key)) { fprintf(stderr,"Pb key destroy\n"); return(1); } return(0); }