0

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

Ulrich Eckhardt
  • 16,572
  • 3
  • 28
  • 55
Santosh Sahu
  • 2,134
  • 6
  • 27
  • 51
  • 2
    Possible duplicate of [How can I propagate exceptions between threads?](http://stackoverflow.com/questions/233127/how-can-i-propagate-exceptions-between-threads) – J.J. Hakala Jan 30 '16 at 18:50
  • 1
    There is no master-slave relation between threads, also no parent-child relation. That said, some questions: Firstly, why do you use the POSIX thread interface instead of C++ threads? Secondly, have you taken a look at "futures" (http://www.cplusplus.com/reference/future/)? – Ulrich Eckhardt Jan 30 '16 at 19:08

0 Answers0