0

I use cpprestsdk (ex-Casablanca) and Boost.Asio, and I need to yield (for other tasks) while waiting for request to complete.

I use this:

void client::make_request(boost::asio::yield_context yield)
{
    http_client client;
    uri = "http://example.com/uri";

    auto request_task = client.request(methods::GET, uri);

    boost::asio::deadline_timer yield_timer(io_service_);
    while (!request_task.is_done())
    {
        // yield, for example for 10 ms
        yield_timer.expires_from_now(default_yield_time_);
        yield_timer.async_wait(yield);
    }

    auto response = request_task.get();

    // ...
    // parse response, etc.
    // ...
}

Is there a more elegant way (not obvious for me sadly :-( ) to do this yielding without using asio timers?

vladon
  • 8,158
  • 2
  • 47
  • 91
  • @MikeMB No, `std::this_thread::wait_for` block the whole system thread, thus blocking asio tasks to execute. (Asio uses its thread pool with system threads to execute tasks, something like so called "green threads".) Simply saying, `async_wait` says the asio scheduler to run other tasks from the tasks queue and return to current tasks after specified amout of time. Imagine you have 100K simultaneous tasks, you cannot run 100K system threads, but asio can run them all (almost) simultaneously using its thread pool. – vladon Dec 03 '15 at 08:07
  • What is your `request_task` ? – Galimov Albert Dec 05 '15 at 19:54
  • @PSIAlt just a requesting any uri from internet – vladon Dec 05 '15 at 19:56
  • i see. Is your `request_task` type is `std::future` or which type is it? If custom, need definition of it. – Galimov Albert Dec 05 '15 at 19:58
  • @PSIAlt It's `pplx::task` from cpprestsdk (Casablanca) library – vladon Dec 05 '15 at 20:00

1 Answers1

0

I think you want something like:

void client::make_request(boost::asio::yield_context yield)
{
    http_client client;
    uri = "http://example.com/uri";

    client.request(methods::GET, uri)
        .then([](web::http::http_response response) {
        // ...
        // parse response, etc.
        // ...
    }
}

I am not sure about your point of yielding. It should be automatic. Asynchronized programming may be different from the way we are used to.

Yongwei Wu
  • 5,292
  • 37
  • 49