- 论坛徽章:
- 0
|
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.区别仅仅是一个是复杂类型的对象,另一个是简单类型.为什么???? |
|