I am trying to send an exception object from slave threads to master thread(main), but I am getting an exception which terminates the main program, since it is not caught. Below is the program:
#include<pthread.h>
#include<iostream>
#include<exception>
using namespace std;
pthread_mutex_t mutex;
pthread_cond_t cond;
class xx{
public:xx(){cout<<"xx constructor called"<<endl;
std::bad_alloc exception; throw exception;}
void display(){cout<<"display called i="<<i++<<endl;}
~xx(){cout<<"xx destructor called"<<endl;}
private: static int i;
};
int xx::i=0;
void* fun1(void *arg)
{
cout<<"fun1 called"<<endl;
pthread_mutex_lock(&mutex);
try{
xx *x1=new xx();
x1->display();
delete(x1);
}
catch(exception &e)
{
cout<<"Exception caught while creating memory for x1"<<e.what()<<endl;
throw e;
}
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
void* fun2(void *arg)
{
cout<<"fun2 called"<<endl;
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond,&mutex);
try{
xx *x2=new xx();
x2->display();
delete(x2);
}
catch(exception &e)
{
cout<<"Exception caught while creating memory for x2"<<e.what()<<endl;
throw e;
}
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
int main(int argc, char *argv[])
{
pthread_mutex_t mutex;
pthread_cond_t cond;
pthread_mutex_init(&mutex,0);
pthread_cond_init(&cond,0);
pthread_t p1,p2;
try{
pthread_create(&p1,NULL,fun1,NULL);
pthread_join(p1,0);
}
catch(exception &e){
cout<<"catch p1"<<endl;
}
try{
pthread_create(&p2,NULL,fun2,NULL);
pthread_join(p2,0);
}
catch(exception &e){
cout<<"catch p2"<<endl;
}
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
Here is the output: **fun1 called
xx constructor called
Exception caught while creating memory for x1std::bad_alloc
terminate called after throwing an instance of 'std::exception'
what(): std::exception
Aborted**
Could any of you please suggest, how the error can be solved
Thanks