2
0
mirror of https://github.com/boostorg/asio.git synced 2026-01-23 17:32:07 +00:00

8 Commits

Author SHA1 Message Date
Christopher Kohlhoff
c83ee18458 Clean up spurious white space. 2024-06-27 23:01:17 +10:00
Christopher Kohlhoff
fc1bdcb2d6 Fix experimental::coro compatibility with Apple clang 15. 2024-06-26 22:49:38 +10:00
Christopher Kohlhoff
35e93e4e90 Update copyright notices. 2023-03-01 23:03:03 +11:00
Christopher Kohlhoff
ff58013a23 Update copyright notices. 2022-03-02 21:23:52 +11:00
Christopher Kohlhoff
ef4e3d873c Add missing #includes for when using separate compilation. 2021-07-08 13:14:30 +10:00
Christopher Kohlhoff
fc486d6530 Fix failure in coro simple_test. 2021-07-07 22:47:10 +10:00
Christopher Kohlhoff
d2ab7b7669 Fix yield input in experimental::coro. 2021-07-04 13:10:27 +10:00
klemens-morgenstern
ecca8406c0 Added experimental::coro class template.
The coro type is a C++20 coroutine primitive for resumable functions,
with the ability to combine both asynchronous waiting (co_await) and
yielding (co_yield) into a single, stateful control flow. For example:

    #include <boostasio.hpp>
    #include <boostasio/experimental/coro.hpp>

    using boost::asio::ip::tcp;

    boost::asio::experimental::coro<std::string> reader(tcp::socket& sock)
    {
      std::string buf;
      while (sock.is_open())
      {
        std::size_t n = co_await boost::asio::async_read_until(
            sock, boost::asio::dynamic_buffer(buf), '\n',
            boost::asio::experimental::use_coro);
        co_yield buf.substr(0, n);
        buf.erase(0, n);
      }
    }

    boost::asio::awaitable<void> consumer(tcp::socket sock)
    {
      auto r = reader(sock);
      auto msg1 = co_await r.async_resume(boost::asio::use_awaitable);
      std::cout << "Message 1: " << msg1.value_or("\n");
      auto msg2 = co_await r.async_resume(boost::asio::use_awaitable);
      std::cout << "Message 2: " << msg2.value_or("\n");
    }

    boost::asio::awaitable<void> listen(tcp::acceptor& acceptor)
    {
      for (;;)
      {
        co_spawn(
            acceptor.get_executor(),
            consumer(co_await acceptor.async_accept(boost::asio::use_awaitable)),
            boost::asio::detached);
      }
    }

    int main()
    {
      boost::asio::io_context ctx;
      tcp::acceptor acceptor(ctx, {tcp::v4(), 54321});
      co_spawn(ctx, listen(acceptor), boost::asio::detached);
      ctx.run();
    }
2021-07-01 21:34:51 +10:00