boost::asio socket sharing across threads in the HTTP Server 3 example
I refer to the code in the Connection class of the boost::asio HTTP Server 3 example http://www.boost.org/doc/libs/1_49_0/doc/html/boost_asio/example/http/server3/connection.cpp
It can be seen that each of the async operations are invoked on a boost::asio::io_service::strand. This ensures that the completion handlers will not be invoked concurrently. However, the example server can be run with multiple threads calling io_service::run which means any of these threads could be used to invoke the handlers. All of the handlers in this example invoke methods on the boost::asio::ip::tcp::socket object. To me, this is sharing the socket object between threads (although not invoking methods on it concurrently).
I can see no synchronization around the socket calls so my question is what mechanism is in place for ensuring that each thread has the same view of the state of the socket object? The documentation clearly states that it is unsafe to share an instance of boost::asio::ip::tcp::socket.
The documentation states that tcp::socket is not thread safe as a shared object.
I use the widely accepted SGI STL definition of thread safety, which is:
The SGI implementation of STL is thread-safe only in the sense that simultaneous accesses to distinct containers are safe, and simultaneous read accesses to shared containers are safe. If multiple threads access a single container, and at least one thread may potentially write, then the user is responsible for ensuring mutual exclusion between the threads during the container accesses.
The key word being simultaneous. So, using multiple threads to access a shared object is fine as long as that access is not concurrent. As an aside, this only matters if one or more of the threads is writing to the shared object.
The state of the socket object is in the process' memory space, which is shared between threads and therefore cannot be inconsistent.
Hope this answers your question!
链接地址: http://www.djcxy.com/p/62674.html上一篇: 关闭后连接成功