简体   繁体   English

当io_service被线程化时,Boost.Asio中的异常处理

[英]Exception handling in Boost.Asio when io_service is threaded

If an app has only one io_service object and is threaded (see code below), what happens if one of the async handlers throw an exception. 如果一个应用程序只有一个io_service对象并且是有线程的(参见下面的代码),那么如果其中一个异步处理程序抛出异常会发生什么。 How does it propagate and more importantly whats the best way to handle them. 它是如何传播的,更重要的是它是处理它们的最佳方式。

std::list< boost::shared_ptr< the_client > > clients_list;
for(int i = 0; i < n_threads; i++)
{
    clients_list.insert(boost::make_shared< the_client >( io_service, server_host, server_port ));
}

for(unsigned int i = 0; i < n_threads; i++)
{
    threads.create_thread(boost::bind(&boost::asio::io_service::run, boost::ref(io_service)));
}

for(std::list< boost::shared_ptr< the_client > >::iterator itr = clients_list.begin(); itr != clients_list.end(); ++itr)
{
    (*itr)->connect_to_server_and_run_statemachine();
}

Here the_client::connect_to_server_and_run_statemachine() sets up the connection to server and initiates the async connection handling. 这里, the_client::connect_to_server_and_run_statemachine()设置与服务器的连接并启动异步连接处理。

I am aware of a question on a similar topic , but that doesn't consider the multi-threaded io_service scenario. 我知道关于类似主题的问题 ,但是这不考虑多线程io_service场景。

Nothing magical happens. 没有什么神奇的事情发生。 If you catch the exception somewhere, then your catch block handles it. 如果你在某个地方捕获异常,那么你的catch块会处理它。 Otherwise, an uncaught exception terminates the process. 否则,未捕获的异常将终止该进程。

How you should handle it depends on what you want to happen. 你应该如何处理它取决于你想要发生什么。 If the exception should never happen, then let it terminate the process. 如果异常永远不会发生,那么让它终止进程。 If you want to eat or handle the exceptions, then write a function that wraps io_service::run in a try / catch block and have the threads run that instead. 如果你想吃或处理异常,那么编写一个在try / catch块中包装io_service::run并让线程运行的函数。

I don't like putting the intelligence that far from the code. 我不喜欢把远离代码的情报放在一边。 My preferred solution is to never have my asynchronous functions throw exceptions unless there's a truly fatal error. 我首选的解决方案是永远不要让我的异步函数抛出异常,除非有一个真正致命的错误。 If an asynchronous function knows how to handle an exception it might throw, then it should catch it. 如果异步函数知道如何处理它可能抛出的异常,那么它应该捕获它。

However, it is perfectly acceptable to wrap run if that makes sense in your application. 但是,如果在您的应用程序中有意义,那么将run包装完全是可以接受的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM