I'm using Boost.Asio for learning asynchronic operations. After reading many articles about this concept im still confused why this piece of code which is part of C++11 Examples from Asio Docs isn't making stack overflow? I just can't imagine the flow of the code in this place. It looks recursive so much, because do_accept(); calls itself again and again... I can imagine that the stack works for 20 clients, but for 2 000 clients? I thought that for Asynchronous operations it is more clear to place acceptor_.async_accept() within a loop and without recursive call inside it. Would it work the same?
Class member "call_nr" is added by me for testing purposes.
The code:
class server
{
public:
server(boost::asio::io_service& io_service, short port)
: acceptor_(io_service, tcp::endpoint(tcp::v4(), port)),
socket_(io_service), call_nr(0)
{
do_accept();
}
private:
void do_accept()
{
acceptor_.async_accept(socket_,
[this](boost::system::error_code ec) // lambda equation
{
using namespace std;
cout << "Call nr " << (++call_nr) << endl;
if (!ec)
{
std::make_shared<session>(std::move(socket_))->start();
}
do_accept();
});
}
int call_nr;
tcp::acceptor acceptor_;
tcp::socket socket_;
};
Aucun commentaire:
Enregistrer un commentaire