c++ - Boost::ASIO - 如何使用 2 个线程来处理接收和发送消息

标签 c++ sockets tcp thread-safety boost-asio

我正在为 Windows 客户端使用 Boost::ASIO 版本 1.52.0。我希望能够专用一个线程来处理所有从服务器接收的消息,然后另一个专用线程来处理所有传出到服务器的消息。我现在为两个线程使用相同的 io_service 对象。我担心的是,当 io_service::run() 方法被调用时,处理传出消息的线程可能会被安排处理一些传入消息调用,反之亦然 -反之亦然。所以,我的问题 - 这可能吗?如果是,那么使用第二个 io_service 对象是否可以解决问题——每个线程一个?有没有更好的方法来设计这个?我试图避免对读取和写入处理程序使用多个线程。

我想确认的另一件事是 - 我读到如果 2 个或更多 async_reads 可以同时完成,则应该使用锁来单线程代码。 async_writes 也是如此。如果 async_read 可以与 async_write 同时执行,是否也应该使用锁,还是线程安全的?

最后一个问题 - 异步方法 - async_connectasync_readasync_write 是否都可以在工作线程之前从不同的线程调用调用了io_service运行方法?

最佳答案

您应该使用单个 io_service,但是您用来调用 io_service::run() 的许多线程也可以为 拥有的异步操作调用处理程序io_service。如果这些处理程序访问共享数据结构,您将需要使用 strand 来确保独占访问。您还需要确保最多一个 write操作

This operation is implemented in terms of zero or more calls to the stream's async_write_some function, and is known as a composed operation. The program must ensure that the stream performs no other write operations (such as async_write, the stream's async_write_some function, or any other composed operations that perform writes) until this operation completes.

read操作

This operation is implemented in terms of zero or more calls to the stream's async_read_some function, and is known as a composed operation. The program must ensure that the stream performs no other read operations (such as async_read, the stream's async_read_some function, or any other composed operations that perform reads) until this operation completes.

每个 socket 都非常出色。

对所有 async_write() 操作使用一个 io_service 对所有 async_read() 操作使用另一个 io_service 是不可能,因为单个套接字由一个作为参数传入的 io_service 服务 constructor .

my experience大多数多 io_service 设计都是由性能和延迟要求驱动的。 HTTP Server 2 example用每个 CPU 的 io_service 来探索这一点。

关于c++ - Boost::ASIO - 如何使用 2 个线程来处理接收和发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14492593/

相关文章:

c++ - C++ 中的 goto 和 RAII

c++ - 模板;构造函数;编译时间

c++ - 这段代码如何正确?

sockets - TCP 是双向的还是全双工的?

c - 如何识别TCP 3次握手中的初始数据包?

java - 如何在 Java8 上自定义 TCP/IP(而非 HTTP)TLS 的主机名检查?

c++ - 是否可以限制 DLL 功能?

是否可以使用本地端口通过 UDP 连接到多个远程对等点?

Java服务器客户端

c - 使用 C 语言套接字编程的简单 HTTP 服务器在 Chrome 上失败