开发者

Should I call socket::connect() from a handler invoked by resolver::async_resolve()?

I'm using a wrapper class to represent a network connection. My implementation contains a method, called async_connect(), which resolves a host/service and connects to a related endpoint (if possible). Something like this:

void tcp::connection::async_connect(std::string const& host, std::string const& service,
    protocol_type tcp = protocol_type::v4())
{
    std::cout << "thread [" << boost::this_thread::get_id() << "] tcp::connection::async_connect()" << std::endl;

    resolver(m_io_service).async_resolve(resolver::query(tcp, host, service),
        boost::bind(&connection::resolve_handler, this, _1, _2));
}

What I want to do know, is establishing the connection from the handler, invoked by the completion of the async_resolve method.

I'm not sure wheter the main thread or the a worker thread is used to invoke the handler. Thus, should I call socket::connect() (this would be the most sensible way if that code would be executed from a worker thread) or start an asynchronous operation again (socket::async_connect() - which should be used when executed by main thread).

void tcp::connection::resolve_handler(boost::system::error_code const& resolve_error,
    tcp::resolver::iterator endpoint_iterator)
{
    std::cout << "thread [" << boost::this_thread::get_id() << "] tcp::connection::resolve_handler()" << std::endl;

    if (!resolve_error)
    {
        boost::system::error_code ec;
        m_socket.connect(*endpoint_iterator, ec);
    }
}

I've observed - from console output - that my resolve_handler is called from a worker thread. So, is it okay to call socket::conne开发者_如何学编程ct() here?


IMO it is good to stick to a single programming model when using asio.

You are free to use asio's synchronous (blocking) calls, where you call a number of methods (resolve, connect, etc) and each one blocks until the result or error is available.

However If you're using the asynchronous programming model, your main or calling thread is typically blocked on io_service::run and the specified handlers are called from a different thread ( as is the case in what you described). When using this programming model you would typically call the next async method from the handler (worker thread), so instead of calling socket::connect, you would call socket::async_connect. It looks to me like you are trying to mix the two different models. I'm not sure what the implications are of mixing the two models (with your calling thread blocked on io_service::run) and you calling a synchronous method from the handler.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜