Navin
Navin

Reputation: 534

Boost async_read_some not exactly asynchronous

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.

Upvotes: 0

Views: 1631

Answers (1)

Rafał Rawicki
Rafał Rawicki

Reputation: 22690

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.

Upvotes: 4

Related Questions