1
votes

Scenario:

  1. Inside object A (thread A), boost::asio::ip::tcp::socket is being read from and written to asynchronously.

  2. Object B (thread B) posts data to object A's data queue.

  3. Object A should write the data in its data queue as soon as possible.

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);

  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.

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? Peforming the write from object B's thread is out of question.

2

2 Answers

0
votes

Well firstly, unless you have a good reason to do I personally wouldn't break it down into 1 thread per object.

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().

Assuming one of the objects is also async_reading, you needn't be writing 0 length datums and creating a loop in the handler. Just schedule the async_write as an when data comes in.

0
votes

"Object A should write the data in its data queue as soon as possible" may be understood as waiting for a C++ future, so you check that answer and that boost::asio::example and last but not least I presume that some improvements will be required on your "data queue" you could have a look to that answer.