When using Boost.Asio stackful coroutines, how can I "manually" yield so that another coroutine or async operation has a chance to run? For example, I need to perform a long computation before sending a response to a command I received from a TCP socket:
asio::spawn(strand_, [this, self](asio::yield_context yield)
{
char data[256];
while (socket_.is_open())
{
size_t n = socket_.async_read_some(boost::asio::buffer(data),
yield);
if (startsWith(data, "computePi"))
{
while (!computationFinished)
{
computeSomeMore();
yield; // WHAT SHOULD THIS LINE BE?
}
storeResultIn(data);
boost::asio::async_write(socket_, boost::asio::buffer(data, n),
yield);
}
}
});
It's simpler than you think:
iosvc.post(yield);
will do the trick.
(iosvc
borrowed from @sehe's sample code)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With