1

我参考了 boost::asio HTTP Server 3 示例的 Connection 类中的代码http://www.boost.org/doc/libs/1_49_0/doc/html/boost_asio/example/http/server3/connection.cpp

可以看出,每个异步操作都是在 boost::asio::io_service::strand 上调用的。这确保不会同时调用完成处理程序。但是,示例服务器可以使用多个调用 io_service::run 的线程运行,这意味着这些线程中的任何一个都可以用于调用处理程序。此示例中的所有处理程序都调用 boost::asio::ip::tcp::socket 对象上的方法。对我来说,这是在线程之间共享套接字对象(尽管不是同时调用它的方法)。

我看不到围绕套接字调用的同步,所以我的问题是有什么机制可以确保每个线程对套接字对象的状态具有相同的视图?文档明确指出共享 boost::asio::ip::tcp::socket 的实例是不安全的。

4

1 回答 1

0

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!

于 2012-06-05T19:25:06.963 回答