#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应该传指针。