加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 无阻塞地开始剩余期货

发布时间:2020-12-16 07:08:26 所属栏目:百科 来源:网络整理
导读:我有一个循环在一个集合,我必须执行昂贵的计算.我希望使用未来的类并行执行此操作.据我所知,async启动线程或推迟它并仅在我调用get()或wait()时启动它.因此,当我没有启动线程并尝试获取结果时,我阻止主线程获得顺序处理.有没有办法启动剩余的延迟进程,所以一
我有一个循环在一个集合,我必须执行昂贵的计算.我希望使用未来的类并行执行此操作.据我所知,async启动线程或推迟它并仅在我调用get()或wait()时启动它.因此,当我没有启动线程并尝试获取结果时,我阻止主线程获得顺序处理.有没有办法启动剩余的延迟进程,所以一切都是并行计算的,并且在调用get()时不会阻塞.

// do the calculations
std::vector<std::future<class>> futureList;
for (auto elem : container)
{
  futureList.push_back(std::async(fct,elem));
}

// start remaining processes

// use the results
for (auto elem : futureList)
{
  processResult(elem.get())
}

谢谢你的帮助.

解决方法

您可以使用:

std::async(std::launch::async,fct,elem)

样品:

#include <iostream>
#include <future>
#include <chrono>
#include <vector>
#include <stdexcept>

bool work() {
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    if( ! (std::rand() % 2)) throw std::runtime_error("Exception");
    return true;
}

int main() {
    const unsigned Elements = 10;

    typedef std::vector<std::future<bool>> future_container;
    future_container futures;

    for(unsigned i = 0; i < Elements; ++i)
    {
        futures.push_back(std::async(std::launch::async,work));
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }

    while( ! futures.empty()) {
        future_container::iterator f = futures.begin();
        while(f != futures.end())
        {
            if(f->wait_for(std::chrono::milliseconds(100)) == std::future_status::timeout) ++f;
            else {
                // Note:: Exception resulting due to the invokation of 
                //        the thread are thrown here.
                //        (See 30.6.6 Class template future)
                try {
                    std::cout << f->get() << 'n';
                }
                catch(const std::exception& e) {
                    std::cout << e.what() << 'n';
                }
                f = futures.erase(f);
            }
        }
    }
    return 0;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读