Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yielding in Boost.Asio Stackful Coroutine

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);
        }
    }
});
like image 252
Emile Cormier Avatar asked Sep 30 '14 18:09

Emile Cormier


1 Answers

It's simpler than you think:

iosvc.post(yield);

will do the trick.

(iosvc borrowed from @sehe's sample code)

like image 170
Jamboree Avatar answered Sep 18 '22 12:09

Jamboree