c++ – Coroutines: Howto call async_* functions from non-coroutine aware librarycode
I’m trying to use asio coroutines in a project which uses an internal library implementing the core functionality.
Lowlevel routines are implemented in concrete implementations of an abstract interface which is used by the library.
The data held by the concrete implementation is normally sufficient to call the lowlevel functions.
#include <boost/asio/io_context.hpp>
#include <boost/asio/co_spawn.hpp>
#include <boost/asio/detached.hpp>
#include <boost/asio/awaitable.hpp>
#include <boost/asio/deadline_timer.hpp>
struct RequestContext
{
virtual void doSomething() = 0;
};
struct AsyncRequestContext : public RequestContext
{
boost::asio::io_context ioc;
void doSomething() override
{
// Do something asynchronous with coroutines ...
boost::asio::deadline_timer timer(ioc);
timer.expires_from_now(boost::posix_time::seconds(5));
// Howto do an async call with cocoutines here?
//co_await timer.async_wait(boost::asio::use_awaitable);
timer.wait();
}
};
// This is in a library which does not know about coroutines
void middle(RequestContext& rctx)
{
rctx.doSomething();
}
int main()
{
AsyncRequestContext rctx;
// Spawn a listening port
boost::asio::co_spawn(
rctx.ioc,
[&rctx]() -> boost::asio::awaitable<void> {
// Call library code
middle(rctx);
co_return;
},
boost::asio::detached);
rctx.ioc.run();
return 0;
}
My problem is, that the coroutine spawn is at the top of the call hierarchy, then the library code is called which calls the lowlevel routines down in the call tree.
I have no clue howto use co_await and the async_* functions in these lower functions without changing the interface.
Read more here: Source link
