线程的资源释放(一)
因为研究线程的资源释放问题,从网上学习了程序,并进行了改写。
看代码:
#include<pthread.h> #include<stdio.h> #include<unistd.h>
using namespace std; pthread_key_t key; void echomsg(void* p){ int t= *(int*)p; printf("destructor excuted in thread %d, param=%d\n ",pthread_self(),t); } void* child1(void* arg){ int *ptid= new int; *ptid=pthread_self(); printf( "child1 %d enter\n ",*ptid); pthread_setspecific(key, (void*)ptid );
sleep(2); printf("child1 %d returns %d\n ",*ptid,*((int*)pthread_getspecific(key))); sleep(5); pthread_exit(NULL); return NULL; } void* child2(void* arg){ int* ptid= new int; *ptid=pthread_self(); printf( "child2 %d enter\n ",*ptid); pthread_setspecific(key,(void*)ptid); sleep(1); printf("child2 %d returns %d\n ",*ptid, *((int*) pthread_getspecific(key))); sleep(5); pthread_exit(NULL); return NULL; } int main(){ pthread_t tid1,tid2; printf( "hello\n "); pthread_key_create(&key,echomsg); pthread_create( &tid1 , NULL, child1 , NULL); pthread_create( &tid2, NULL, child2 , NULL); //pthread_join(tid1,NULL); //pthread_join(tid2,NULL); sleep(30); pthread_key_delete(key); printf( "main thread %d exit\n ",pthread_self()); return 0; }
因为主进程的睡眠时间很长(30秒),所以大家两个线程都有机会完成资源释放部分的代码。