Given a function that receives a continuation callback
void async_write(string_view buffer, function<void(error_code)> callback);
where such callback might be called from a different thread,
is the only and the best option to wrap such function in a closure and call it from await_suspend ?
template<typename F>
struct Awaitable {
F f;
std::coroutine_handle<> resume;
error_code result;
void await_suspend(std::coroutine_handle<> resume) {
this->resume = resume;
f([this](error_code result) {
this->result = result;
this->resume();
});
}
};
// Usage
auto result = co_await Awaitable{[&](auto callback) {
async_write(buffer, callback);
}};
If we call async_write before await_suspend, we'd have to pass it a temporary callback that might be executed in-parallel with await_suspend, thus requiring a costly synchronization (e.g. atomic_flag).
Boost.Asio uses similar callables to implement their async_* functions, however such approach looks quite uncanny, hence the question. Maybe there is another way to use functions with callbacks in coroutines.