C ++ 11线程概念有例外

时间:2017-03-08 02:28:44

标签: c++ multithreading c++11 exception-handling

据我所知,当使用c ++ 11线程时如果没有在子线程上调用join,如果父线程先前死掉,子线程可能无法完成对父线程持有的资源的处理,我也理解在子进程与父进程连接之前,父线程中会抛出异常,同样的情况也会发生。   我在下面写了一段代码,以便在异常发生时了解概念。

typedef struct thread_method{
    void operator()(const std::string& message){
        for(int i = 0; i < 100000;i++);
        std::cout <<'\n'<<message;
    }
}thread_method;

void throwException() {
        std::cout <<'\n'<<"throwException";
        throw "Exception thrown";
}

void threadHandlingOne(void){
    std::string message = "Hello World";
    std::thread m_thread1 ( (thread_method()) ,
                            std::ref(message) );    

    try {
      throwException();      
    }catch (const char* err_message){
      std::cout <<'\n'<<err_message;
      m_thread1.join();
      throw err_message;
    }
}

int main(int argc , char** argv){
    threadHandlingOne();
    return 0;
}

然而,在运行程序时,我会继续获得2个不同的输出。

1 throwException
  Exception thrown

2 Hello World
  throwException

两个输出都没有意义。对于(1)为什么父线程不等待子进程完成,因为连接被调用。对于(2)子线程运行正常,但为什么没有调用catch?

0 个答案:

没有答案