0

我正在尝试制作具有协程结果的地图。
我搜索了一个示例,展示了如何获得协程的未来。
之后我需要生成任务以将它们与 asio 一起使用。
这是协程的代码:

std::map<std::string, boost::shared_ptr<HTTPResponse>> create_tasks(const symbols_enum& symbol, date day)
{
    int start = 0;

    if (is_dst(day))
    {
        start = 1;
    }

    ostringstream oss;
    oss << symbol;
    std::string url_currency{oss.str()};
    std::ostringstream().swap(oss); // swap m with a default constructed stringstream
    std::string url_year{day.year()};

    stringstream ss_month;
    ss_month << setw(2) << setfill('0') << ((day.month().as_number()) - 1);
    string url_month{ ss_month.str() };
    std::stringstream().swap(ss_month); // swap m with a default constructed stringstream

    stringstream ss_day;
    ss_day << setw(2) << setfill('0') << day.day().as_number();
    string url_day{ ss_day.str() };
    std::stringstream().swap(ss_day); // swap m with a default constructed stringstream

    std::string URL{ protocol_host_URL+"/"+"datafeed"+"/"+ url_currency +"/"+ url_year +"/"+ url_month +"/"+ url_day +"/" };

    HTTPClient client;


    std::map<std::string, std::shared_ptr<HTTPRequest>> requests_variables;
    std::map<std::string, boost::shared_ptr<HTTPResponse>> tasks;

    for (int hour = 0;hour < 24;hour++)
    {
        stringstream ss_hour;
        ss_hour << setw(2) << setfill('0') << hour;
        string url_hour{ ss_hour.str() };
        std::stringstream().swap(ss_hour); // swap m with a default constructed stringstream
        URL = URL + url_hour +"h_ticks.bi5";

        std::string request_name = "request_" + std::to_string(hour);
        requests_variables[request_name] =  client.create_request(hour, URL);

        //requests_variables[request_name]->execute();//must be coroutine and i think it should be normal coroutine
        coroutine<boost::shared_ptr<HTTPResponse>>::pull_type response_future_coroutine_pull(requests_variables[request_name]->execute);
        tasks[request_name] = response_future_coroutine_pull.get();         

    }
    //tasks = [asyncio.ensure_future(get]


        return tasks;

    }

这部分代码显示了我需要完成未来任务的方式。
它基于 python 获取协程期货的方式。
我不明白如何在 C++ 中做到这一点。
我部分使用了 asio,但为了使用 for 循环,我想制作将包含在 for 循环中的协程,并且它的异步函数将在 asio 服务中运行。
我不知道我的想法是否正确。我特别需要的是一个如何制作协程期货容器的例子......

4

1 回答 1

0

你不需要boost::coroutine这里。你想要的是std::aysnc

std::map<std::string, std::future<boost::shared_ptr<HTTPResponse>>> tasks;
for (...) {
    ...
    tasks[request_name] = std::async(&HTTPRequest::execute, client.create_request(hour, URL));
}

当您想等待响应时

std::map<std::string, boost::shared_ptr<HTTPResponse>> responses;
for (auto& pair : tasks) {
    response[pair.first] = pair.second.get();
}
于 2018-04-19T09:03:22.273 回答