boost::asio::spawn 将一统C++网络库

boost::asio::spawn 将一统C++网络库

(金庆的专栏)

boost::asio::spawn()创建一个协程,使C++网络编程大大简化,
个人认为这使得 asio 成为C++首选网络库。

boost::asio::spawn(my_strand, do_echo);
一般输入2个参数,参数1是 io_service 或者是 strand,
参数2是协程函数,类型如下:
void coroutine(boost::asio::yield_context yield);

在协程函数中调用各个异步IO,异步操作将挂起协程,待异步操作完成后会自动继续协程。

示例:
    // See: doc/html/boost_asio/example/cpp11/spawn/echo_server.cpp
    try
    {
        boost::asio::io_service io_service;
        using std::placeholders::_1;
        using std::ref;
        boost::asio::spawn(io_service,
            std::bind(LoopAccept, ref(io_service), unPort, _1));
        io_service.run();
    }
    catch (std::exception& e)
    {
        std::cerr << "Exception: " << e.what() << "\n";
    }


LoopAccept() 是实际的协程函数

// Accept coroutine.
static void LoopAccept(boost::asio::io_service& io_service,
    unsigned short port, boost::asio::yield_context yield)
{
    using boost::asio::ip::tcp;
    tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), port));

    for (;;)
    {
        boost::system::error_code ec;
        std::shared_ptr pSession(
            new CAsioSvrSession(io_service));
        acceptor.async_accept(pSession->GetSocket(), yield[ec]);
        if (ec) continue;
        pSession->Go();  // Will spawn read and write coroutine.
    }
}

你可能感兴趣的:(C/C++)