小编pet*_*tke的帖子

用自己的版本替换std :: async但std :: promise应该在哪里生效?

我正在使用vc2011,事实证明std :: async(std :: launch :: async,...)有点儿错误(有时它不会产生新线程并且并行运行它们,而是重用线程和一个接一个地运行任务).当我进行昂贵的网络呼叫时,这太慢了.所以我想我会编写自己的异步函数.我虽然陷入困境,std :: promise应该在哪里生活?在1)线程函数中,2)异步函数,或3)调用函数.

码:

#include <future>
#include <thread>
#include <iostream>
#include <string>
#include <vector>

std::string thFun() {
    throw std::exception("bang!");
    return "val";
}

std::future<std::string> myasync(std::promise<std::string>& prms) {
//std::future<std::string> myasync() {
    //std::promise<std::string> prms; //needs to outlive thread. How?

    std::future<std::string> fut = prms.get_future();
    std::thread th([&](){
        //std::promise<std::string> prms; //need to return a future before...
        try {
            std::string val = thFun();

            prms.set_value(val);

        } catch(...) {
            prms.set_exception(std::current_exception());
        }

     });

    th.detach();
    return fut;
}

 int main() {

    std::promise<std::string> prms; //I really …
Run Code Online (Sandbox Code Playgroud)

c++ multithreading future promise c++11

11
推荐指数
2
解决办法
1696
查看次数

标签 统计

c++ ×1

c++11 ×1

future ×1

multithreading ×1

promise ×1