gpt4 book ai didi

c++ - asio::this_coro::executor 的实现是什么

转载 作者:行者123 更新时间:2023-12-05 06:06:16 25 4
gpt4 key购买 nike

在一个协程函数中,我们可以添加auto ex = co_await asio::this_coro::executor;来获取这个协程的执行者。但是当我想了解它的定义时,我发现了这个:

/// Awaitable type that returns the executor of the current coroutine.
struct executor_t
{
ASIO_CONSTEXPR executor_t()// ASIO_CONSTEXPR is defined constexpr
{
}
};

/// Awaitable object that returns the executor of the current coroutine.
#if defined(ASIO_HAS_CONSTEXPR) || defined(GENERATING_DOCUMENTATION)
constexpr executor_t executor;
#elif defined(ASIO_MSVC)
__declspec(selectany) executor_t executor;
#endif

为什么executor awiatable?

最佳答案

如解释here ,当到达 co_await 时, co_await 后面的表达式被转换为可等待的:

otherwise, if the current coroutine's Promise type has the member function await_transform, then the awaitable is promise.await_transform(expr)

查看 asio/include/asio/experimental/coro.hpp 中定义的 coro_promise 类型我们确实可以找到以 this_coro::executor_t 作为参数的此方法的重载:

  auto await_transform(this_coro::executor_t) const
{
struct exec_helper
{
const executor_type& value;

constexpr static bool await_ready() noexcept { return true; }

constexpr static void await_suspend(coroutine_handle<>) noexcept {}

executor_type await_resume() const noexcept { return value; }
};

return exec_helper{executor_};
}

这不会暂停协程,因为 exec_helperawait_ready() 总是返回 true。相反,它会立即调用 await_resume(),正如您在上面看到的那样,它会返回存储在当前 promise 中的执行程序。

因此 this_coro::executor_t 的唯一目的是用于重载解析。 this_coro::cancellation_state_t 有另一个重载,它有一个类似的空定义,目的相同。

全局变量 constexpr executor_t executor; 在那里,以便您可以传递 this_coro::executor 而不是 this_coro::executor_t{}到协程中的 co_await 运算符。

关于c++ - asio::this_coro::executor 的实现是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65821773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com