c++ - 处理程序抛出异常后是否需要重置 asio::io_service ?

标签 c++ boost exception boost-asio

虽然 boost 文档说

After the exception has been caught, the run(), run_one(), poll() or poll_one() call may be restarted without the need for an intervening call to reset()

我有不同的经历。

在异常处理程序中,我发现 io_service 处于停止状态,并且事实上任何后续添加异步工作的尝试都会失败,因此以下 run() 调用会立即退出。

这与我正在做的事情非常相似:

...
io_service ios;
do_receive(); // adds some async work to ios 
do try
{
    ios.run();
    break;
}
catch (std::exception const &)
{
    assert (ios.stopped()); //<----- ASSERTION DOESN'T TRIGGER. i.e ios is stopped
    ios.reset();            //<----- ...So I need to do this otherwise next call
                            //<----- to do_receive() fails to add more async work
                            //<----- causing next loop iteration's run() invocation
                            //<----- to exit immediately

    do_receive(); //same as above, adds async work to ios
}
while(1);

在尝试添加新的异步工作之前添加对 io_service 的 reset() 的调用似乎已经解决了问题,但我看不出在有多个线程调用 run() 的情况下这将如何扩展。

如果任何处理程序抛出,catch block 将在该线程上下文中调用重置,我猜这会严重扰乱所有其他正在进行的操作。

我在 boost 文档中做错了什么或者遗漏了什么吗?

谢谢, 安德里亚。

最佳答案

如果没有更多工作要做,io_service 将自行停止;这可能就是这里发生的事情。如果您想防止这种情况,可以通过创建 io_service::work 对象来实现。只要该对象存在,io_service 就不会自行停止。

关于c++ - 处理程序抛出异常后是否需要重置 asio::io_service ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19033604/

相关文章:

c++ - boost program_options 生成一个 Klocwork MLK.MUST

java - 为什么Java编译器允许在throws部分列出方法不可能抛出的异常

python-3.x - os.path.exists 返回 false 但不会在 try/except block 中引发异常

c++ - 是什么导致在电脑崩溃之前将空字符写入文件?

c++ - 如何覆盖 C++ STL 中分配器类中构造方法的默认行为

c++ - 并排显示卡片

windows - Boost spirit : assertion fails under Windows but not Linux. 为什么?

c++ - 在使用中删除 boost 功能

Android加载一些数据

c++ - 在 C++ 中对数组进行洗牌和平方的函数的问题