关于这篇文章: Why do I need strand per connection when using boost::asio?
我关注的是关于异步调用的声明: "但是,多个线程并发调用是不安全的"
这个例子: http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/example/cpp11/chat/chat_client.cpp
如果我将 main 称为“线程 1”,将生成的线程 t 称为“线程 2”,那么看起来线程 1 正在调用 async_write(假设没有 write_in_progress),而线程 2 正在调用 async_read。我错过了什么?
最佳答案
在官方chat example , chat_client::write()
通过 io_service::post()
将工作推迟到 io_service
,这将:
- 请求
io_service
通过当前正在调用poll()
的线程执行给定的处理程序,poll_one()
,run()
,或io_service
上的 - 不允许在调用函数中调用给定的处理程序(例如
chat_client::write()
)
run_one()
函数
由于只有一个线程在运行 io_service
,并且所有套接字读取、写入和关闭操作仅从已发布到 io_service
的处理程序启动,因此程序满足 socket
的线程安全要求.
class chat_client
{
void write(const chat_message& msg)
{
// The nullary function `handler` is created, but not invoked within
// the calling function. `msg` is captured by value, allowing `handler`
// to append a valid `msg` object to `write_msgs_`.
auto handler = [this, msg]()
{
bool write_in_progress = !write_msgs_.empty();
write_msgs_.push_back(msg);
if (!write_in_progress)
{
do_write();
}
};
// Request that `handler` be invoked within the `io_service`.
io_service_.post(handler);
}
};
关于c++ - 将 boost async API 与多个线程一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37781385/