类中的递归函数或竞争条件?

时间:2013-08-28 01:26:46

标签: c++ boost

在以下代码中,私有函数handle_read_content使用asio::async_read,这取决于handle_read_content。这会调用递归行为还是创建竞争条件?

class client
{
public:
    //constrcutor, io_service,   server name?  path?

    client(asio::io_service& io_service,
           const std::string& server, const std::string& path)
    : resolver_(io_service),
    socket_(io_service)
    {
        //form request, connection close header server close the socket
        //std:ostream reuest_stream


        // Form the request. We specify the "Connection: close" header so that the
        // server will close the socket after transmitting the response. This will
        // allow us to treat all data up until the EOF as the content.
        std::ostream request_stream(&request_);
        request_stream << "GET " << path << " HTTP/1.0\r\n";
        request_stream << "Host: " << server << "\r\n";
        request_stream << "Accept: */*\r\n";
        request_stream << "Connection: close\r\n\r\n";

        // Start an asynchronous resolve to translate the server and service names
        // into a list of endpoints.
        //tcp:resolver:query

        tcp::resolver::query query(server, "http");

        resolver_.async_resolve(query,
                                boost::bind(&client::handle_resolve, this,
                                            asio::placeholders::error,
                                            asio::placeholders::iterator));
    }

private:


    void handle_read_content(const asio::error_code& err)
    {
        if (!err)
        {
            // Write all of the data that has been read so far.
            std::cout << &response_;

            // Continue reading remaining data until EOF.
            asio::async_read(socket_, response_,
                             asio::transfer_at_least(1),
                             boost::bind(&client::handle_read_content, this,
                                         asio::placeholders::error));
        }
        else if (err != asio::error::eof)
        {
            std::cout << "Error: " << err << "\n";
        }
    }

    tcp::resolver resolver_;
    tcp::socket socket_;
    asio::streambuf request_;
    asio::streambuf response_;
};

1 个答案:

答案 0 :(得分:1)

这不是递归的,handle_read_content是一个回调函数,将在async_read操作完成时调用。

http://www.boost.org/doc/libs/1_54_0/doc/html/boost_asio/reference/async_read/overload1.html

这是async_read的工作方式,这是它正在做的事情:

  1. 阅读一些数据
  2. 当读取操作完成时,boost调用调用handle_read_content
  3. 调用新的async_read ...然后再次启动进程......直到发生错误。