Add cancel_after example.

This commit is contained in:
Christopher Kohlhoff
2026-07-06 23:46:46 +10:00
parent 489e469823
commit 9cfa357fe8
4 changed files with 50 additions and 4 deletions
+2 -1
View File
@@ -532,7 +532,8 @@ Coroutines.
* [@boost_asio/example/cpp20/coroutines/echo_server_with_deferred_default.cpp]
* [@boost_asio/example/cpp20/coroutines/refactored_echo_server.cpp]
* [@boost_asio/example/cpp20/coroutines/chat_server.cpp]
* [@boost_asio/example/cpp20/coroutines/timeout.cpp]
* [@boost_asio/example/cpp20/coroutines/timeout_cancel_after.cpp]
* [@boost_asio/example/cpp20/coroutines/timeout_watchdog.cpp]
[heading Invocation]
+2 -1
View File
@@ -37,4 +37,5 @@ exe echo_server_with_default : echo_server_with_default.cpp ;
exe echo_server_with_deferred : echo_server_with_deferred.cpp ;
exe echo_server_with_deferred_default : echo_server_with_deferred_default.cpp ;
exe refactored_echo_server : refactored_echo_server.cpp ;
exe timeout : timeout.cpp ;
exe timeout_cancel_after : timeout_cancel_after.cpp ;
exe timeout_watchdog : timeout_watchdog.cpp ;
@@ -0,0 +1,44 @@
//
// timeout_cancel_after.cpp
// ~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2026 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <boost/asio.hpp>
using namespace boost::asio;
using ip::tcp;
using namespace std::literals::chrono_literals;
awaitable<void> echo(tcp::socket sock)
{
char data[4196];
for (;;)
{
auto n = co_await sock.async_read_some(buffer(data), cancel_after(10s));
co_await async_write(sock, buffer(data, n), cancel_after(10s));
}
}
awaitable<void> listen(tcp::acceptor& acceptor)
{
for (;;)
{
co_spawn(
acceptor.get_executor(),
echo(co_await acceptor.async_accept()),
detached);
}
}
int main()
{
io_context ctx;
tcp::acceptor acceptor(ctx, {tcp::v4(), 54321});
co_spawn(ctx, listen(acceptor), detached);
ctx.run();
}
@@ -1,6 +1,6 @@
//
// timeout.cpp
// ~~~~~~~~~~~
// timeout_watchdog.cpp
// ~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2026 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//