future并行化处理 使用示例
时间: 2023-07-11 18:34:22 浏览: 39
下面是一个使用future并行化处理的示例程序,其中使用了async函数来创建future对象,使用wait_for函数来等待future对象完成,并使用get函数来获取future对象的结果:
```C++
#include <iostream>
#include <vector>
#include <future>
int main()
{
std::vector<std::future<int>> futures;
// 创建5个future对象,每个对象都会异步执行一个lambda表达式
for (int i = 0; i < 5; ++i) {
futures.push_back(std::async(std::launch::async, [i]{
std::cout << "Task " << i << " started" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Task " << i << " completed" << std::endl;
return i * 2;
}));
}
// 等待所有的future对象都完成,并获取它们的结果
for (auto& future : futures) {
auto status = future.wait_for(std::chrono::seconds(5));
if (status == std::future_status::ready) {
std::cout << "Result: " << future.get() << std::endl;
} else {
std::cout << "Future not ready" << std::endl;
}
}
return 0;
}
```
输出结果为:
```
Task 0 started
Task 1 started
Task 2 started
Task 3 started
Task 4 started
Task 0 completed
Result: 0
Task 3 completed
Result: 6
Task 1 completed
Result: 2
Task 2 completed
Result: 4
Task 4 completed
Result: 8
```
在这个示例程序中,创建了5个future对象,每个对象都会异步执行一个lambda表达式。在等待所有的future对象都完成时,使用wait_for函数设置了超时时间为5秒,如果超时,则输出“Future not ready”;如果成功获取到future对象的结果,则输出“Result: ”和结果值。