将异常对象从从属线程传递到主线程

时间:2016-01-30 18:43:33

标签: c++ multithreading exception posix

我正在尝试从从属线程向主线程(main)发送异常对象,但是我得到一个异常终止主程序,因为它没有被捕获。以下是该计划:

 #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;
 }  

这是输出:     ** fun1叫

 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**

你们中的任何人都可以建议,如何解决错误

谢谢

0 个答案:

没有答案