std::future
and std::vector>
in Multithreaded Programmingstd::future
和 std::vector>
Multithreading in C++ allows for parallel execution of code. Using std::future
and std::vector
, you can manage asynchronous operations more efficiently.
C++中的多线程允许代码并行执行。使用std::future
和std::vector
,你可以更有效地管理异步操作。
std::future
Basicsstd::future
provides a mechanism to access the result of asynchronous operations. It’s often used with std::async
to run tasks in parallel.
std::future
基础std::future
提供了一种访问异步操作结果的机制。它通常与std::async
一起使用,以并行运行任务。
std::vector>
for Multiple TasksWhen you have multiple tasks to run in parallel, storing each task’s std::future
in a std::vector
simplifies task management.
std::vector>
处理多个任务当你有多个任务需要并行运行时,将每个任务的std::future
存储在一个std::vector
中可以简化任务管理。
This example demonstrates launching multiple tasks asynchronously and waiting for all to complete:
此示例演示了如何异步启动多个任务并等待全部完成:
#include
#include
#include
void doWork(int id) {
// Simulate some work.
std::cout << "Task " << id << " completed.\n";
}
int main() {
std::vector<std::future<void>> futures;
for (int i = 0; i < 5; ++i) {
futures.emplace_back(std::async(std::launch::async, doWork, i));
}
for (auto& fut : futures) {
fut.get(); // Wait for each task to complete
}
std::cout << "All tasks completed.\n";
return 0;
}
std::future
and std::vector
simplify handling asynchronous tasks in C++, making your code more efficient and easier to manage.
std::future
和std::vector
简化了C++中异步任务的处理,使你的代码更高效、更易于管理。