Verwendung von asio::async_initiate mit asio::co_spawn und asio::any_io_executorC++

Programme in C++. Entwicklerforum
Anonymous
 Verwendung von asio::async_initiate mit asio::co_spawn und asio::any_io_executor

Post by Anonymous »

Ist garantiert, dass das Token auf dem Executor ex im folgenden Code aufgerufen wird?

Code: Select all

template 
auto async_from_awaitable(asio::any_io_executor ex,
asio::awaitable aw,
CompletionToken&& token)
{
using token_type = std::decay_t;

// Materialize the token as an lvalue to satisfy async_initiate on MSVC
token_type tk(std::forward(token));

return asio::async_initiate(
[ex, aw = std::move(aw)](auto&& handler) mutable {
// Spawn the coroutine; on completion, deliver via the handler
asio::co_spawn(
ex,
std::move(aw),
// co_spawn completion for non-void: void(std::exception_ptr, T)
[h = std::forward(handler)]
(std::exception_ptr ep, T value) mutable
{
if (ep) {
try {
std::rethrow_exception(ep);
}
catch (const boost::system::system_error& se) {
std::move(h)(se.code(), T{});
return;
}
catch (...) {
std::move(h)(
make_error_code(boost::system::errc::operation_canceled), T{});
return;
}
}
std::move(h)({}, std::move(value));
}
);
},
tk // pass as lvalue
);
}

asio::awaitable compute_answer(bool success)
{
if (success)
{
co_return 42;
}
else
{
// Create an error_code from the generic category
boost::system::error_code ec =
make_error_code(boost::system::errc::permission_denied);

// Throw as system_error
throw boost::system::system_error(ec, "Access denied while opening file");
}
}

int main()
{
asio::io_context io;
auto ex = io.get_executor();

auto handler = [&context](error_code ec, int value)
{
if (ec)
{
context.logger.debug(awl::format()

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post