zoukankan      html  css  js  c++  java
  • 线程的资源释放(一)

    因为研究线程的资源释放问题,从网上学习了程序,并进行了改写。

    看代码:

    #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秒),所以大家两个线程都有机会完成资源释放部分的代码。

  • 相关阅读:
    Reversion windows 2008 R2 STD to Datacenter
    NetAPP常用操作
    firefox解决flash崩溃
    物理和虚拟兼容性RDM的区别
    网络嗅探器Wireshark
    子网掩码在线计算换算及算法
    Debian中文字体安装
    快算24点,POJ(3983)
    第九十八周,搜索24点
    两次DFS,POJ(1481)
  • 原文地址:https://www.cnblogs.com/gaojian/p/2651298.html
Copyright © 2011-2022 走看看