LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 708|回复: 7

capture the exception thrown from second thread

[复制链接]
发表于 2006-2-8 23:35:30 | 显示全部楼层 |阅读模式
say I have two thread A and B, A is the main thread, B is initilized and started from A by using following code
[PHP]
void A::runB()
{
     try
    {
          B *b = new B();
          b->run(); /* the second thread start running */
     }
     catch(Exception error)
     {
     }
}

[/PHP]
After b starts running, an exception is raised, how can I make the try-catch block in A::runB() catch that exception raised in B?????

Thank you
发表于 2006-2-8 23:48:12 | 显示全部楼层
Perhaps impossible.
Post by http://gcc.gnu.org/bugs.html#known

Exceptions don't work in multithreaded applications.

    You need to rebuild g++ and libstdc++ with --enable-threads. Remember, C++ exceptions are not like hardware interrupts. You cannot throw an exception in one thread and catch it in another. You cannot throw an exception from a signal handler and catch it in the main thread.
回复 支持 反对

使用道具 举报

 楼主| 发表于 2006-2-9 00:04:52 | 显示全部楼层
Then, how should I handle these kind of exceptions in a multi-threaded application. what is the typical way to do it ???

anyone knows?
回复 支持 反对

使用道具 举报

发表于 2006-2-9 00:10:46 | 显示全部楼层
Perhaps you should just catch the exception in the thread that throws it.
回复 支持 反对

使用道具 举报

 楼主| 发表于 2006-2-9 00:39:23 | 显示全部楼层
but there is some error messge in the exception class, and those message I want to pass to the main thread, how can I do this ???
回复 支持 反对

使用道具 举报

发表于 2006-2-9 11:57:59 | 显示全部楼层
Since different threads don't share same resources, it may be impossible to achieve in the program itself, or I don't know how to manage that.

You may use shared resources such as files, but maybe as a sacrifice in portability.

Anyone have better suggestion?
回复 支持 反对

使用道具 举报

 楼主| 发表于 2006-2-9 14:27:12 | 显示全部楼层
here is a solution pop up into my mind, I can make A and B inherited from C, and in C, declare a variable called Exception error, whenever an exception is thrown in either A or B, error variable is set to that exception type... well, of course, I have to ensure that the exclusive access to error in C....

Does this sound reasonable and doable ????
回复 支持 反对

使用道具 举报

发表于 2006-2-9 22:23:45 | 显示全部楼层
IMHO, it is still impossible since A and B are still at different threads. A in thread A still cannot be informed by B in thread B, because they don't share recourses.
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表