开始剩余的期货而不阻塞
Start remaining futures without blocking
本文关键字:开始 更新时间:2023-10-16
我在一个集合上有一个循环,在那里我必须执行昂贵的计算。我想使用未来的类并行地执行此操作。据我所知,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;
}
您可以执行以下操作:(http://coliru.stacked-crooked.com/a/005c7d2345ad791c)
创建此功能:
void processResult_async(std::future<myClass>& f) { processResult(f.get()); }
然后
// use the results
std::vector<std::future<void>> results;
for (auto& elem : futureList)
{
results.push_back(std::async(std::launch::async, processResult_async, std::ref(elem)));
}
相关文章:
- 当回溯以零开始时,如何调试崩溃
- 根据用户输入用字母填充矢量,并将"开始"和"结束"放在四肢
- 如何从头开始创建 avi 文件?
- 为什么 -mmacosx-version-min=10.10 不阻止使用标记为从 10.11 开始的函数?
- 自一周开始以来的秒数?
- 一旦双簧管录制开始,主 UI 线程就会被阻止
- GStreamer在开始任何播放之前进行搜索
- 使 std::fstream 写入文件末尾,但从头开始读取
- 如何以毫秒为单位获取开始时间和 now() 之间的毫秒差异(以 C++为单位?
- 哪个C++规范开始支持 std::vector
- 如何继续读取不同功能中的文件,而不是从头开始再次读取文件?
- 如何在 c++ 中确定一条指令(以字节为单位)在哪里结束,另一条指令从哪里开始?
- 如何在调试中通过传递引用开始
- 如何使用 picojson.h 在 c++ 中从头开始创建 json 对象
- 从特定键开始遍历地图
- 列表的有效性在插入后开始迭代器
- 尝试从头开始实现Leetcode的FizzBuzz多线程问题。收到"libc++abi.dylib: terminating"错误
- 试图修复一个错误,该错误不会让我开始编程其余部分
- 甚至在开始执行之前出现分段错误
- 为什么 Glib::VariantBase::store 方法破坏了给定缓冲区的开始