免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2425 | 回复: 2
打印 上一主题 下一主题

结束线程时不释放对象为什么会出问题? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-03-13 15:07 |只看该作者 |倒序浏览
pthread_mutex_t      _Mutex;
pthread_cond_t      _Condition;

class ThreadResource
{
        public :
                ThreadResource() { cout<<"ThreadResource ctor"<<endl;}
                ~ThreadResource() { cout<<"ThreadResource dtor"<<endl;}
               
                void showMessage(const string& str) { cout<<"ThreadResource "<<str<<endl; }
};

void * child1(void *arg)
{
        cout<<"child1 begin running!!!"<<pthread_self()<<endl;
        pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) ;
        pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
        pthread_mutex_lock   ( &_Mutex );
        cout<<"child 1 get lock"<<endl;
         while(true)
         {
                 sleep(2);
          cout<<"child 1 working ..."<<endl;
        }
          pthread_mutex_unlock   ( &_Mutex );
         pthread_exit(0);
}

void * child2(void *arg)
{
        cout<<"child2 begin running!!! "<<pthread_self()<<endl;
        pthread_detach(pthread_self());
        pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) ;
        pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
        ThreadResource * res = new ThreadResource;
//        char * buf = new char[1000];
        while(true)
          ;
}

int main(void)
{
   pthread_t tid1,tid2;
   int iCancelRet = 0;
   cout<<"EINVAL = "<<EINVAL<<endl;
   pthread_mutex_init( &_Mutex, NULL );
   pthread_cond_init(&_Condition, NULL);
   
   pthread_create(&tid1,NULL,child1,NULL);
   sleep(2);
   pthread_create(&tid2,NULL,child2,NULL);
   
   iCancelRet = pthread_cancel(tid2);
   cout<<"iCancelRet="<<iCancelRet<<endl;
//  cout<<"join result 2 = "<<pthread_join(tid2,NULL)<<endl;
   cout<<"join thread 1 now"<<endl;
   cout<<"EDEADLK="<<EDEADLK<<endl;
   cout<<"join result 1 = "<<pthread_join(tid1,NULL)<<endl;
   cout<<"join thread 1 ok"<<endl;
   pthread_cond_destroy(&_Condition);
   pthread_mutex_destroy( &_Mutex );
   
return 0;
}
代码如上,问题是这样的:
如果child2 中 ThreadResource * res = new ThreadResource;不被注释的话,主程序运行到cout<<"join result 1 = "<<pthread_join(tid1,NULL)<<endl;就会core掉,但是如果child2 中 char * buf = new char[1000];不被注释,ThreadResource * res = new ThreadResource;被注释的时候就不会core.区别仅仅是一个是复杂类型的对象,另一个是简单类型.为什么????

论坛徽章:
0
2 [报告]
发表于 2007-03-14 09:01 |只看该作者
没有人知道?

论坛徽章:
0
3 [报告]
发表于 2007-03-14 10:35 |只看该作者
您既然调用了pthread_detach(pthread_self());
那您这个线程退出时就应该释放线程的私有数据,否则可能造成内存丢失,至于为什么char*为什么不会CORE,这应该是编译器做的不同处理吧。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP