简体   繁体   English

C ++ Boost.Asio-TCP套接字异步写入

[英]C++ Boost.Asio - tcp socket asynchronous write

Scenario: 场景:

  1. Inside object A (thread A), boost::asio::ip::tcp::socket is being read from and written to asynchronously. 在对象A(线程A)内部,异步读取和写入boost :: asio :: ip :: tcp :: socket。

  2. Object B (thread B) posts data to object A's data queue. 对象B(线程B)将数据发布到对象A的数据队列中。

  3. Object A should write the data in its data queue as soon as possible. 对象A应尽快将数据写入其数据队列中。

How to achieve the third point efficiently? 如何有效地达到第三点?

Right now I'm doing this: 现在我正在这样做:

  1. There might be no data in the queue. 队列中可能没有数据。

  2. socket->async_send(data, handler); socket-> async_send(数据,处理程序);

  3. inside handler: back to point two. 内部处理程序:回到第二点。

I'm worried that this approach is highly inefficient - calling async_send with zero-length data most of the time until actual data can be sent. 我担心这种方法效率很低-大多数情况下,使用零长度数据调用async_send直到可以发送实际数据为止。

Might it be that a better approach would be to have an additional thread inside object A that performs synchronous writes on the socket as soon as new data is posted? 可能是更好的方法是在对象A内有一个附加线程,以便在发布新数据后立即在套接字上执行同步写操作吗? Peforming the write from object B's thread is out of question. 从对象B的线程执行写操作是毫无疑问的。

Well firstly, unless you have a good reason to do I personally wouldn't break it down into 1 thread per object. 首先,除非您有充分的理由,否则我个人不会将其分解为每个对象1个线程。

Instead, have a shared io_service (just pass it in by reference to both A and B ctors. Then have a single thread on the io_serice.run() . 相反,拥有一个共享的io_service (只需通过引用A和B io_serice.run()来传递它即可。然后在io_serice.run()上有一个线程。

Assuming one of the objects is also async_reading, you needn't be writing 0 length datums and creating a loop in the handler. 假设其中一个对象也是async_reading,则无需编写长度为0的基准并在处理程序中创建循环。 Just schedule the async_write as an when data comes in. 只需将async_write安排async_write时输入数据。

对象A应该尽快将数据写入其数据队列中 ”可能被理解为等待C ++的未来,因此您检查答案并确认boost :: asio :: example ,最后但并非最不重要的一点是,我认为有一些改进您的“ 数据队列 ”中将要求您可以看看该答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM