在多个线程中使用提升异步 API
using boost async API's with multiple threads
关于这篇文章:为什么使用 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_client::write()
通过 io_service::post()
将工作推迟到io_service
,这将:
- 请求
io_service
通过当前正在调用poll()
、poll_one()
、run()
或run_one()
函数的线程执行给定的处理程序io_service
- 不允许在调用函数中调用给定的处理程序(例如
chat_client::write()
)
由于只有一个线程在运行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);
}
};
相关文章:
- 用于访问容器<T>数据成员的正确 API
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 如何使用Luacneneneba API正确读取字符串和表参数
- C++MySQL C api用户输入行
- 如何使用 AWS Transcribe C++ API 中的'StartTranscriptionJobRequest'?
- 将std::string传递给WriteConsole API
- EvtExportLogneneneba API正在将远程计算机的事件日志保存到远程PC本身.如何将其保存到主机
- 在gtest.中使用fff.h模拟系统API
- 有没有任务栏API可以立即应用注册表更改
- C++win32 API创建多个类似视口的窗口
- 使用libcurl提交批量url的正确BING Api POST url是什么
- 如何使用适用于 S3 的 AWS 开发工具包 cpp 异步 API?
- 使用boost :: Beast进行CPU重的REST API,我是否应该使用异步或同步方式来实现它们以期望延迟
- 在多个线程中使用提升异步 API
- 将第三方异步 API 与 Cap'n Proto RPC 集成的好方法是什么?
- 设计一个结合同步和异步操作的c++ API
- 在异步API (c++)中,如何保证API在调用回调之前返回
- 将波形加载到内存中,然后使用Win32 API异步播放声音
- 异步事件:已定义链接器错误[Windows Update API]
- 同步和异步api