在多线程编程中使用 `std::future` 和 `std::vector<std::future<void>>`

Using std::future and std::vector> in Multithreaded Programming

在多线程编程中使用 std::futurestd::vector>

Introduction

Multithreading in C++ allows for parallel execution of code. Using std::future and std::vector>, you can manage asynchronous operations more efficiently.

介绍

C++中的多线程允许代码并行执行。使用std::futurestd::vector>,你可以更有效地管理异步操作。

std::future Basics

std::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一起使用,以并行运行任务。

Using std::vector> for Multiple Tasks

When 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中可以简化任务管理。

Example

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;
}

Suitable Cases

  • Parallel Data Processing: Ideal for operations that can be executed concurrently, such as processing multiple files.
  • Asynchronous I/O Operations: Useful for non-blocking I/O operations.

适用情况

  • 并行数据处理:适用于可以并发执行的操作,如处理多个文件。
  • 异步I/O操作:用于非阻塞I/O操作。

Conclusion

std::future and std::vector> simplify handling asynchronous tasks in C++, making your code more efficient and easier to manage.

结论

std::futurestd::vector>简化了C++中异步任务的处理,使你的代码更高效、更易于管理。

你可能感兴趣的:(C++CommonSense,开发语言,C++)