3 ms·
With a coroutine you may not necessarily have to do as many gymnastics as with callbacks. You can turn a push operation ("call me back using this function with
by nly 7y ago
With a coroutine you may not necessarily have to do as many gymnastics as with callbacks. You can turn a push operation ("call me back using this function with a newly connected socket"), in to a pull operation ("get me a newly connected socket")
For example, here's an awaitable that just wraps ASIO callback for accepting new connections:
auto async_accept (tcp::acceptor& acceptor, tcp::socket& socket) {
struct Awaitable {
tcp::acceptor& acceptor;
tcp::socket& socket;
boost::system::error_code ec;
bool await_ready() {
return false;
}
void await_suspend (std::experimental::coroutine_handle<> coro) {
return acceptor.async_accept (
socket, [this, coro](boost::system::error_code ec) mutable {
this->ec = ec;
coro.resume();
}
);
}
auto await_resume() {
return ec;
}
};
return Awaitable{acceptor, socket};
};