2013-01-08 55 views
0

我有一个C++应用程序,我使用Boost线程来提供并发性。基本示例如下:C++如何在线程产生函数中提升线程抛出的异常

processingThreadGroup->create_thread(boost::bind(process, clientSideSocket, this)); 

这里,processingThreadGroup是一个共享指针在升压线程池和工艺是我需要调用的函数。 clientSideSocket和这是应该传递给进程函数的参数。

在处理函数内部,如果检测到错误,我会抛出一个自定义异常。进程函数将数据发送到远程服务器。所以我的问题是,如何将这个错误传递给调用堆栈?清理完成后,我想关闭系统。试过以下内容:

try { 
    processingThreadGroup->create_thread(boost::bind(process, clientSideSocket, this)); 
} catch (CustomException& exception) { 
    //code to handle the error 
} 

但没有奏效。任何想法如何正确地做到这一点?

谢谢!

+0

它看起来很像'std :: async' _does/do_do_,它使用'future'来处理返回值和异常。 –

回答

1

要传播返回值和例外,您应该使用future s。这是一个简单的方法:

// R is the return type of process, may be void if you don't care about it 
boost::packaged_task<R> task(boost::bind(process, clientSideSocket, this)); 
boost::unique_future<R> future(task.get_future()); 

processingThreadGroup->create_thread(task); 

future.get(); 

这有一些陷阱,你必须记住。首先,task的使用期限必须延长异步执行process。其次,get()将阻塞,直到task完成,并在成功结束时返回其值,或者在抛出异常时传播异常。您可以使用各种功能来检查future的状态,如has_value(),has_exception(),is_ready()

+0

感谢您的建议。我是新的推动者,并会阅读期货。 – Izza

+0

@Izza:您发布的代码不是真实代码,是吗? 'bind'调用将尝试创建一个_copy_套接字... –

+0

clientSideSocket只是一个识别套接字的整数。所以我不认为这是一个问题。 – Izza