7

I'm pretty new in asio framework, so please be kind. I've investigated several boost asio example and found that people use async call like this:

void read()
{
    async_read(socket_, boost::asio::buffer(&user_[0], user_.size()),
       boost::bind(&Connection::handle_user_read, this,
       placeholders::error, placeholders::bytes_transferred));
}
void handle_user_read(...)
{
    ...
    read();
    ...
}

I think this code is not safe because it uses multiple recursion. So it cant be used when a lot of read operations are performed because of call stack overflow. I'm not 100% sure in this and unable to find any similar thoughts from other people.

Could anyone please explain this in details?

sehe
  • 374,641
  • 47
  • 450
  • 633
Vladimir Tsyshnatiy
  • 989
  • 1
  • 10
  • 20

2 Answers2

5

I suppose the read() function just adds new async read request to the I/O queue and exits immediately, so there's no recursion in this code.

I mean, the read() doesn't call Connection::handle_user_read directly. It just store the function pointer inside the IO queue. This function is going to be invoked asynchronously by external code when some new chunk of data will be available.

Minor Threat
  • 2,025
  • 1
  • 18
  • 32
1

It's not recursion, it's chained async operations; be aware of threading issues:

Why do I need strand per connection when using boost::asio?

Community
  • 1
  • 1
sehe
  • 374,641
  • 47
  • 450
  • 633