0

This is my server code:

socket_.async_read_some(boost::asio::buffer(data_read.data(), Message::header_length),
    boost::bind(&TcpConnection::handle_read_header, shared_from_this(),
    boost::asio::placeholders::error));

If i write a the the following code in a loop

boost::thread::sleep(boost::posix_time::seconds(2));

in the 'handle_read_header' function which is called by the above 'async_read_some' the whole thread is waiting till the sleep end. So when another request comes in it is not handled until the sleep finishes. Isn't is suppose to asynchronously handles each requests? I am new to boost and C++. Please let me know if i have mentioned anything wrong.

Navin
  • 554
  • 2
  • 9
  • 31
  • Actually, even while "sleeping" Boost::asio will still continue to read asynchronously. It is just that, if a handler is running and you use one only one thread, Asio has no way to notify you about the the completion of the read. How would you expect it to behave ? – ereOn Jun 18 '12 at 08:33
  • @ereOn are you saying the the methods i call inside 'handle_read_header' should be in a in a different thread ? and ereOn aren't async_read_some creates new thread for each handler? – Navin Jun 18 '12 at 09:06
  • @ereOn if i call a thread inside the handler by the time the thread finishes the socket might have changed by the new request. – Navin Jun 18 '12 at 09:16
  • 1
    Boost Asio documentation states that all callbacks (handlers) will be called from the exact same thread(s) `io_service::run()` was called. Nothing else. Whether Asio uses threads or `select()` for handling asynchronous reads/writes shouldn't matter to you as it will still behave the same from the user's perspective. That is, if you call `io_service::run()` in a single-thread, you can't expect the handlers to be called simultaneously. – ereOn Jun 18 '12 at 09:33

1 Answers1

4

Read scheduled with async_read_some is realized in the thread which called io_service::run(). If you have only one thread it will wait for completing one read handler, before starting another one.

You can make a thread pool, by running more threads with io_service::run() or make the execution of read handler shorter.

Rafał Rawicki
  • 22,324
  • 5
  • 59
  • 79
  • thanks for the quick reply, i tried 'io_service::run()' but it seems that way its not exactly working properly. but yes i am trying to shorten the execution of read handler. – Navin Jun 18 '12 at 07:33
  • @Navin what is not working properly? Maybe you didn't synchronize access to shared variables? – Rafał Rawicki Jun 18 '12 at 07:39