我正在审查Boost网站上的HTTP Server 3示例.
你能解释我为什么需要strand每个连接吗?正如我所看到的,我们read_some只在read-event的处理程序中调用.所以基本上read_some调用是顺序的,因此不需要strand(第3段的第2项说同样的事情).多线程环境中的风险在哪里?
我正在使用boost附带的一个示例http服务器(在doc/html/boost_asio/example/cpp03/http/server,或者在http://www.boost.org/doc/libs/1_55_0/) doc/html/boost_asio/examples/cpp03_examples.html#boost_asio.examples.cpp03_examples.http_server).
该示例打开一个接受器套接字并侦听,剥离请求对象的请求.服务器还有一个boost asio signal_set,用于注册信号处理程序,并在收到SIGINT或SIGTERM时从io_service中取消所有asio请求.按CTRL-C键接收信号,io_service调出一个handle_stop()函数,然后调用.close()所有函数asio::ip::tcp::sockets.整个服务器正常关闭,io_service.run()呼叫退出,程序结束.
我希望能够在一个线程中启动这个http服务器,然后以编程方式取消它而不是使用信号.这样做的可接受方式是什么?我删除了signal_set信号处理程序,然后在另一个线程上启动了服务器.它可以很好地处理来自新线程的http请求.如何从另一个线程中阻止它?asio::ip::tcp::socket::close()从另一个线程调用是否安全?文档不清楚,只是这样做感觉非常,非asio-ish.实际上,当我尝试这样做时,只要我还没有接受任何http请求,它就能正常工作.如果我甚至处理了一个http请求,那么进程会在boost中崩溃:
> test_ssl_server_sa.exe!boost::detail::sp_counted_base::add_ref_lock() Line 81 + 0x3 bytes C++
test_ssl_server_sa.exe!boost::detail::shared_count::shared_count(const boost::detail::weak_count & r={...}) Line 578 + 0x12 bytes C++
test_ssl_server_sa.exe!boost::shared_ptr<http::server::connection>::shared_ptr<http::server::connection><http::server::connection>(const boost::weak_ptr<http::server::connection> & r={...}) Line 405 + 0x3f bytes C++
test_ssl_server_sa.exe!boost::enable_shared_from_this<http::server::connection>::shared_from_this() Line 49 + 0xc bytes C++
test_ssl_server_sa.exe!http::server::connection::handle_handshake(const boost::system::error_code & error={...}) Line 83 + 0x11 bytes C++
test_ssl_server_sa.exe!boost::_mfi::mf1<void,http::server::connection,boost::system::error_code const &>::operator()(http::server::connection * p=0x004b8fe8, const boost::system::error_code & a1={...}) Line 165 + …Run Code Online (Sandbox Code Playgroud) 我在 Boost ASIO 文档和 StackOverflow 上读到的所有内容都表明我可以async_accept通过调用close接受器套接字来停止操作。但是,当我尝试执行此操作时,处理程序not_socket中出现间歇性错误。async_accept我做错了什么或者 Boost ASIO 不支持这个吗?
(注意:我在 Windows 7 上运行并使用 Visual Studio 2015 编译器。)
\n\n我面临的核心问题是async_accept接受传入连接的操作与我对close. 即使使用显式或隐式的链时也会发生这种情况。
请注意,我对的调用async_accept严格发生在对 的调用之前close。我得出的结论是,竞争条件存在于我的调用close与 Boost ASIO 中接受传入连接的底层代码之间。
我已经包含了演示该问题的代码。该程序重复创建一个接受器,连接到它,然后立即关闭该接受器。它期望async_accept操作成功完成或被取消。任何其他错误都会导致程序中止,这就是我间歇性看到的情况。
为了同步,程序使用显式链。然而,对的调用与操作的效果close不同步,因此有时接受器在接受传入连接之前关闭,有时在之后关闭,有时两者都不是\xe2\x80\x94,因此出现问题。async_accept
这是代码:
\n\n#include <algorithm>\n#include <boost/asio.hpp>\n#include <cstdlib>\n#include <future>\n#include <iostream>\n#include <memory>\n#include <thread>\n\nint main()\n{\n boost::asio::io_service ios;\n auto work …Run Code Online (Sandbox Code Playgroud)