Boost ASIO和co_await-是否与任何第三方回调一起使用? [英] Boost ASIO and co_await- use with any third party callback?

查看:80
本文介绍了Boost ASIO和co_await-是否与任何第三方回调一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简单的功能:

awaitable<std::size_t> write(const std::vector<uint8_t>& data)
{
    auto token = co_await this_coro::token();

    return co_await async_write(serialport_, buffer(data), token);
}

可以使用 co_await write(my_data)等待.

当我使用任何异步Boost ASIO函数时,此方法都有效.

This works when I use any async Boost ASIO function.

如果异步功能是从一些不相关的库中进行回调的话,该如何使用这种模式?

How would one go about using this pattern if the async function was some callback from some unrelated library?

代码可能看起来像:

awaitable<bar> foo()
{
   auto token = co_await this_coro::token();

   return co_await third_party_callback;
}

用法类似于 auto result = co_await foo().

我很难弄清楚什么是最简单/最干净的方法.

I am having difficulties figuring out what the simplest/cleanest way to this is.

奖金问题:Boost ASIO的协程API(例如令牌),Boost的协程库和协程TS之间是什么关系?

推荐答案

要使用另一个库,另一个库将必须为协程TS创建支持,否则您(或其他人)将必须在之间提供胶水"代码协程TS需要工作的内容以及第三方库.

To use another library, the other library would have to create support for coroutines TS or you (or someone else) would have to provide the "glue" code between the what the coroutines TS requires to work and the 3rd party library.

一旦您了解了协程TS的工作原理,可能无需花太多精力.

The effort to do this may not much once you understand what the coroutines TS requires to work.

您可以在协同例程TS上阅读刘易斯贝克文章.现在有很多人都在谈论这个主题的视频和文章.一旦了解了需求,支持其他等待类型就很简单,只要您有某种方法可以在协同例程完成时发出信号,并且您还有某种上下文可以继续协同例程完成.

You could read Lewis Baker articles on the co routines TS. There are lots of videos and articles from lots of people covering the topic now. Once you understand the requirements, supporting other await types is simple so long as you have some way to signal when the co routine completes and you also have some sort of context to continue the co routine completes on.

如果第三方库只是做一些繁重的处理工作.您可能希望将工作包装到某种类型的Boost Future/Promise设置中,并使用已经存在的Boost线程粘合代码,例如

If the third party library is just do some heavy processing work. You may like to wrap the work into some sort of boost future / promise setup and use the boost thread glue code that is already around like this one (although the boost asio examples predate the boost asio experimental support.

实验性标记是协例行程序TS和boost asio之间的胶水"代码(据我所知).它与Boost的协程库无关.

The experimental token is the "glue" code between the co routine TS and boost asio (as far as I can tell). It has nothing to do with Boost's coroutine library.

Boost ASIO支持3种协同例程类型:

Boost ASIO supports 3 co routine types:

  • Stackless Coroutines - Boost ASIO own light weight co routine library using pre-processor macros (been around for a long time now)
  • Stackful Coroutines - Uses Boost Coroutine library
  • Coroutines TS Support (experimental) - Uses CO Routine TS (which is also stackless)

这篇关于Boost ASIO和co_await-是否与任何第三方回调一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆